2
votes

I've seen a lot of posts asking about which overloaded constructor to select using Unity, but my question is a little different and I can't figure out the answer. I have the following class inheriting an Interface (partial code):

public class UnitOfWork : IUnitOfWork
{
    private DbContext _context;

    public UnitOfWork(DbContext context)
    {
        _context = context;
    }

}

So now I'm trying to use unity to resolve the concrete type to the interface like below:

container.RegisterType<IUnitOfWork, UnitOfWork>();

However, I need to pass in my Entity Framework context to that concrete type upon being resolved. I want to do something like this:

container.RegisterType<IUnitOfWork, UnitOfWork(new AdventureWorks2008R2Entities())>();

Of course I know the code above is incorrect, and have read about using the InjectionConstructor class, but I don't think that's applicable here.

So my question is, how do I define the value of that constructor on the UnitOfWork class when resolving the concrete type using Unity IoC?

Thanks!

2

2 Answers

2
votes

You need to add a registration for a DbContext: container.RegisterType<DbContext, AdventureWorks2008R2Entities>();

Remember, one major feature of an IoC container is to auto-wire. You don't need to tell each registration what instance to use. You just register interfaces/classes to implementations and let it put stuff in the right place (and override in the ideally rare occasions where you're doing something abnormal).

2
votes

I was able to use the InjectionConstructor class as I had inteded and the following registration worked well:

container.RegisterType<IUnitOfWork, UnitOfWork>(new InjectionConstructor(new AdventureWorks2008R2Entities()));

The following link helped me understand this a bit better:

Registering Injected Parameter and Property Values