Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity: Implicit ResolvedParameter for unnamed registrations

The UserService constructor has two parameters, a IUnitOfWork and a IUserRepository:

public UserService(IUnitOfWork unitofWork, IUserRepository userRepository) 
{ ... }

I am using named registrations to differentiate between multiple instances of IUnitOfWork, so when registering the UserService with the Unity container, I need to explicitly specify the parameters using an InjectionConstructor:

container.RegisterType<IUserService, UserService>(
    new InjectionConstructor(
        new ResolvedParameter<IUnitOfWork>("someContext"),
        new ResolvedParameter<IUserRepository>()
    )
);

Is it possible for new ResolvedParameter<IUserRepository>() to be omitted? I would like Unity to implicitly deduce this parameter since there is no need for a named registration. The code would look like this:

container.RegisterType<IUserService, UserService>(
    new InjectionConstructor(
        new ResolvedParameter<IUnitOfWork>("someContext")
    )
);

This would be done is any case when I don't need to use the InjectionConstructor.

like image 973
Dave New Avatar asked Feb 20 '14 10:02

Dave New


1 Answers

Would you be willing to decorate your constructor with the DependencyAttribute from Unity? This solution is straight forward, built-in, and lets you pick and chose named dependency. But it does 'dirty' your constructor with Unity goo.

public UserService(
    [Dependency("someContext")]IUnitOfWork unitofWork, 
    IUserRepository userRepository) 
{ ... }

Another solution would be to write a custom BuilderStrategy and UnityContainerExtension. This could be done with a bit more work.

like image 128
TylerOhlsen Avatar answered Oct 23 '22 00:10

TylerOhlsen