Posts Tagged ‘ Design Patterns

Generic factory and repositories: Part 2 revisited

This post is part of a series:
- Generic factory and repositories: Part 2 revisited
- Generic factory and repositories: Part 2
- Generic factory and repositories: Part 1
- WCSF, Repositories and Unit of Work?

In Part 2 I discussed my implementation for a SimpleRepositoryFactory. I said that I wasn’t quite happy with the implementation of the factory class, as I would have to adjust my Create() method every time I would add a new repository to the project. At first I was looking for a solution that would let me pass a typeof() into the generic parameter of the InternalRepositoryFactory. For example, I wanted to do something like:

InternalRepositoryFactory<typeof(I), typeof(C)>.Create();

Of course this doesn’t work. Generics need to be resolved at compile time and therefore it’s impossible to create the code I wanted. Or is it?

There is one way of dynamically inserting types into a generic class and/ or method during runtime: reflection! I might be a bit of a nerd, but I love working with reflection. It can do everything! This doesn’t mean I use it inappropriately, I just happen to like the challenge of diving into completely unreadable code and making stuff work! :)

I managed to adjust my SimpleRepositoryFactory in such a way that I would never need to touch the Create() method again. Even if I add new repositories to the project at a later stage!

public static class SimpleRepositoryFactory
{
    private static Dictionary<Type, Type> repositoryTypes =
        new Dictionary<Type,Type>()

    /// <summary>
    /// Creates repository object based on its interface
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="args"></param>
    /// <returns></returns>
    public static T Create<T>(params object[] args)
    {
        if (repositoryTypes.ContainsKey(typeof(T)))
        {
            // Create InternalRepositoryFactory<I, C>.
            Type internalFactory =
                typeof(InternalRepositoryFactory<,>);
            internalFactory = internalFactory.MakeGenericType(
                typeof(T), repositoryTypes[typeof(T)]);

            // Get the Create() method from the
            // InternalRepositoryFactory.
            MethodInfo method = internalFactory.GetMethod(
                "Create", BindingFlags.Static |
                BindingFlags.NonPublic);

            // Invoke the Create() method and return the result.
            // For some reason I need to wrap 'args' into a new
            // object[]?
            return (T)method.Invoke(
                internalFactory, new object[] {args});
        }
        else
        {
            throw new Exception("Type: " + typeof(T)
                + " does not exist in dictionary. Register"
                + " the type mappings first by using the"
                + " RegisterTypeMapping method.");
        }
    }

    /// <summary>
    /// Registers the repository types, marking them as
    /// available to use with the RepositoryFactory.
    /// </summary>
    /// <typeparam name="I">Interface type of object.</typeparam>
    /// <typeparam name="C">Concrete type of object.</typeparam>
    public static void RegisterTypeMapping<I, C>()
    {
        // Only add the type mapping if it doesn't exist.
        if (!typeMapping.ContainsKey(typeof(I)))
        {                
            typeMapping.Add(typeof(I), typeof(C));
        }
    }
}

There are multiple downsides to this code.

Even though I don’t have to touch the Create() method any more, I have to maintain the internal dictionary with definitions. I have moved the problem to a different area in my code. However, the positive side of this is that I can’t break the implementation by accident. If I need to be able to instantiate a new repository, I will add a new definition to the dictionary, using the RegisterTypeMapping() method.

Another downside is that I’ve made the code a lot more complex! This does not improve readability or maintainability at all! Imagine a colleague, unschooled in the ways of reflection, needs to make changes to this code while I am on holidays… the poor bastard would have a very hard time trying to figure it all out!

I can imagine the performance takes a hit as well. I have no clue how much, as I haven’t bothered to measure. However, I think we can all agree that using reflection to resolve types and invoke methods is a bit more costly than simply invoking a method with generics.

I have no idea whether I should use this code or not. I’ve wrote it, I’ve seen it works and I enjoyed the challenge of figuring it out, but all the potential downsides make me scratch my head whether or not I should revert the code back to the way it was. I did write this post in case you, as reader, might really need to do something similar. Therefore I will let you make up your own mind and I won’t tell you what’s right or wrong. Just remember to sit down and think it over again when you suspect you need to resolve generics dynamically at runtime!

Lastly, I’d like to point out that I’ve moved far away from my original intent of developing a factory to create repositories, instead it has become a very generic class that can instantiate any sort of object as long as it implements an interface that can be returned. I’m not even sure if it can actually be classified as a factory pattern any more. SimpleRepositoryFactory seems a very inadequate name as it does not describe the actual implementation!

Generic factory with repositories: Part 2

This post is part of a series:
- Generic factory and repositories: Part 2 revisited
- Generic factory and repositories: Part 2
- Generic factory and repositories: Part 1
- WCSF, Repositories and Unit of Work?

Yesterday I posted my musings on using the factory pattern to instantiate my repositories without needing to have a reference to the actual repository class, but only the interface. This morning I made some progress and I have actually managed to create some working code. Some of the code, especially the SimpleRepositoryFactory, can do with a little refinement. However, the basic principle seems to be working and that is all that matters at the moment.

The Repositories

Let’s start with the beginning and have a look at how I defined my repository classes and interfaces.

public interface IRepository<T> where T : class
{
    IQueryable<T> AsQueryable();
    IEnumerable<T> GetAll(string[] includes = null);
    IEnumerable<T> GetMany(Expression<Func<T, bool>> where,
        string[] includes = null);
    T GetSingle(Expression<Func<T, bool>> where,
        string[] includes = null);
    T GetFirst(Expression<Func<T, bool>> where,
        string[] includes = null);
    void Delete(T entity);
    void Add(T entity);
}
public abstract class Repository<T> : IRepository<T>
    where T : class
{
    private IUnitOfWork unitOfWork;

    public Repository(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }

    #region IRepository members
    // For the sake of simplicity, I'll leave the implementation
    // of the IRepository interface away. I might put up a source
    // code zip package later!
    #endregion
}

Now that I have the crude basics for a repository, it’s time to put them to work.

The following code demonstrates how to declare a repository that uses the IRepository interface and the abstract Repository base class. Because the IUserRepository interface implements the IRepository interface, I will be able to call all methods declared in IRepository by talking to my IUserRepository. This is pretty neat, since I won’t ever need to know anything about the concrete implementations when I start implementing the code in my (web) application.

public interface IUserRepository : IRepository<User>
{
}
public class UserRepository : Repository<User>, IUserRepository
{
    public UserService(IUnitOfWork unitOfWork)
        : base(unitOfWork)
    {
    }
}

The generic factory

Now that I’ve shown you the basics of my repository, I will show you the implementation of my SimpleRepositoryFactory. Mind you, it’s nothing special and it’s exactly what the name suggests; simple.

public static class SimpleRepositoryFactory
{
    public static T Create<T>(params object[] args)
    {
        if (typeof(T) == typeof(IUserService))
        {
            // Excuse me for the code mark-up here!
            return (T)InternalRepositoryFactory<IUserService,
                UserService>.Create(args);
        }
        else
        {
            return default(T);
        }
    }
}

The downside of using this approach is that I will have to edit the SimpleRepositoryFactory with every new repository class I might add. A little inconvenient, but for now it suits me fine as I will only need to add it in the Create() method of the factory by using another else-if statement. You might notice that this class calls InternalRepositoryFactory to actually instantiate the object.

The InternalRepositoryFactory is actually a very generic object factory. It will be able to create any object, as long as the object implements the specified interface.

internal static class InternalRepositoryFactory<I, C> where C : I
{
    internal static I Create(params object[] args)
    {
        return (I)Activator.CreateInstance(typeof(C), args);
    }
}

Using the factory!

Now that I’ve got all the pieces of the puzzle, it’s time to start putting it all together. Notice how I will still be able to use my repositories and unit of work as I described here! Not only that, but I’m also using interfaces instead of instantiating concrete implementations of my repositories!

using (TransactionScope ts = new TransactionScope())
{
    using (IUnitOfWork uof = new ConcreteUnitOfWork())
    {
        // Get reference to UserRepository.
        IUserRepository ur =
            SimpleRepositoryFactory.Create<IUserRepository>(uof);

        // Get all users.
        List<User> users = ur.GetAll().ToList();

        // You can create more repositories here and
        // do additional work using this unit of work
        // and transaction scope!

        // We're done!
        uof.Commit();
        ts.Complete();
    }
}

Conclusion

I’m not really sure if this approach is correct, but for now I have solved the problem that I posted about yesterday in Part 1. This solution will allow me to create different modules and have interaction between them by only using their interfaces without needing to instantiate concrete implementations that would make my code too tightly coupled. I’m not quite happy with the implementation of SimpleRepositoryFactory and I will continue to look for a more elegant solution.

Generic factory with repositories: Part 1

This post is part of a series:
- Generic factory and repositories: Part 2 revisited
- Generic factory and repositories: Part 2
- Generic factory and repositories: Part 1
- WCSF, Repositories and Unit of Work?

My previous post was about using WCSF in combination with repositories and a unit of work. I didn’t have any clear answers then and I don’t have any clear answers now. It doesn’t matter any more though, since I decided to drop WCSF entirely and pursue my own implementation of a modular web application, based on MVP, where I can still use my repositories as I would like.

The reasons why I’m doing this don’t matter. It has some very solid grounds, but I won’t discuss them as it’s not in the scope of this post.

Let’s take a look at the situation I’m faced with for a new proof of concept project:

I need to be able to make a simple modular web application. Users would need to be able to enter meeting-reports as well as enter activities. However, some issues in the meeting will have led to activities needing to be completed. So it should also be possible to create activities when entering a meeting-report.

In this case I will have two modules in my system: MeetingReports and Activities. The MeetingReports module will need to use the ActivitiesRepository within the Activities module to be able to create activities.

I won’t go into details, but WCSF had this nicely covered by working with dependency injection and interface libraries. That’s a practice from WCSF that I would like to adapt. However, I can’t simply make a reference from MeetingReports to the activties interfaces. I will have to instantiate a concrete class at some point!

What if I would be able to make a generic factory that instantiates repositories for me and returns their interface? I would be able to use the repositories without needing to know anything about their implementations.

I don’t have any concrete code yet (what a surprise!), but I would imagine something similar to this might be very possible:

using (IUnitOfWork uof = new UnitOfWork)
{
    IMeetingReportRepository irr =
        RepositoryFactory.Create<IMeetingReportRepository>(uof);
    irr.Insert(meetingReport);

    IActionRepository iar =
        RepositoryFactory.Create<IActionRepository>(uof);

    // Save all activities.
    foreach (Activity a in meetingReport.Activities)
    {
        iar.Insert(a);
    }

    uof.Commit();
}

The factory class would know how to instantiate ActionRepository based on the fact that its create method has been called with an IActionRepository generic! This way the factory will do the concrete instantiation while the activities module will only see, and use, the interface!

Hopefully I will be able to show some working C#-code soon, so stay tuned (yes, again)…

WCSF, Repositories and Unit of Work?

This post is part of a series:
- Generic factory and repositories: Part 2 revisited
- Generic factory and repositories: Part 2
- Generic factory and repositories: Part 1
- WCSF, Repositories and Unit of Work?

In my research for designing and implementing modular web applications, I’ve come across the Web Client Software Factory. I’ve already briefly touched this subject in a previous post. It heavily uses the Composite Web Application Block to implement a Model-View-Presenter approach for a web application. It allows developers to compose applications from different pieces  of software (modules). One of the advantages of this approach is that these modules can be developed independently from each other by different teams of developers. Another advantage is that the entire web application consists of separate blocks of software that are loosely coupled. I’m sure you’ve heard that term used by someone before!

As I was evaluating WCSF I stumbled on an interesting question. A question which I have no answer to yet.

In the past I’ve successfully used Microsoft’s Entity Framework. It’s relatively straight forward to implement a Repository Pattern in combination with a Unit of Work. If you have no idea what I’m talking about, here is a nice example. Admittedly, it’s an implementation for NHibernate, but it can just as easily be implemented for EF. The beauty of this approach was that I could use a single ObjectContext and pass it on to multiple repositories. This allowed me to use different repository classes in the same TransactionScope.

Here’s a quick example to show what I mean:

using (TransactionScope ts = new TransactionScope())
{
    // Create unit of work.
    using (IUnitOfWork uof = new ConcreteUnitOfWork())
    {
        // Create repositories and pass unit of work.
        OrderRepository or = new OrderRepository(uof);
        CustomerRepository cr = new CustomerRepository(uof);

        // place order in the system.
        or.Insert(customer.Order);

        // update order history for the customer.
        cr.UpdateHistory(customer);

        // So far, so good! Save all the changes.
        uof.Commit();
        ts.Complete();
    }
}

This is a simple piece of code that shows a single transaction over multiple repositories. In this scenario I had complete control over creating an ObjectContext and releasing its resources (IUnitOfWork implements IDisposable which will clean up any resources). In this way I had full control over creating a fresh ObjectContext for each new business transaction and automatically disposing it when the code finishes executing the using-statement.

I wanted to have the same functionality with implementing WCSF. I’ve had a good long look at the sample OrderManagementRI implementation that comes with the WCSF sources. It’s an excellent example of how they implement repositories and use them as a service within a module. I’ve been able to recreate a similar scenario in my proof of concept application, but I found I no longer have any control on my IUnitOfWork since it is created and passed on to the repositories by using Dependency Injection.

I’ve been searching on the web for a solution, but so far I’ve not found it yet. I’d like to have the same functionality with my IUnitOfWork. I want to be able to create a new one to pass along to multiple repositories in a transaction, while still having the benefits of the modular service approach of WCSF. I have a feeling that I should be able to create something much more to my liking if only I understood more of both WCSF and Dependency Injection principles.

To be continued (again)…

Creating modular web applications

Before you read on, if you stumbled on this link through a search engine I will not waste your time and say I won’t be telling you how to do it. Instead, I’m going to share my experience of researching this topic.

It all sounds so beautiful. The idea of creating a web application that is built by separate blocks of functionality that can be developed independently of each other, but are still smart enough to work together if necessary. I started out thinking that I wouldn’t be the first person to have this brilliant idea and that there would be plenty helpful topics to help me get my journey underway. I had absolutely no idea what I would get myself into! Believe me when I tell you that implementing this idea is easier said then done!

I’ve always considered myself an able software developer who likes to dabble with getting projects started and setting up their architectures. Who have I been kidding?! Shortly after starting my research it was evident that there’s no out-of-the-box solution readily available. There are in fact a lot of ways to achieve this goal.

In the past week(s) I have found that my knowledge did not carry me as far as I had expected it would. I’ve read various books on Design Patterns and supposed that I understood most of the concepts I had read about. After having read many articles, I’ve been beaten to death with a lot of complicated words. Separation of Concerns, Model View Controller, Model View Presenter (and all their various little brothers and sisters), Inversion of Control, Dependency Injection and I could continue adding terms this list! Eventually I found myself reading up on Workflow Foundation and Service Oriented Architectures as well.

It made me scratch my head. I’ve read about most and heard about others, but found that my knowledge doesn’t extend past that. I’m hazy on the actual implementation of all these patterns and there’s such an abundance of literature to read that I feel I’m getting deviated from my original goal. However, getting to that goal will require me to dust off some of my knowledge and start polishing it to a shine again… It’s a nasty little circle that I will have to break out of. In any case it’s proving the point of what I was trying to convey to my old employer, it’s important to know about design patterns and their implementations!

At the moment I’m edging towards the possibility of a proof of concept implementation using the Model View Presenter design pattern in combination with ASP.NET WebForms. As far as I can tell right now this is going to be the most flexible way and reap the best of both worlds: seperation of concerns with an MVP approach (probably aided by Composite Web Application Block), combined with the strength and productivity WebForms can bring in terms of controls, such as Telerik.

Perhaps I will follow up on this topic later when I have a clearer vision on which approach to take and why.