Search code examples
c#unity-containerfactory

Unity with factory method who need parameters


I want to register a type in an Unity container with a factory method who needs paramters. These parameters are to be resolved by unity but only at runtime.

Factory method code :

public static IApp Create(IOne, ITwo) {...}

Register code :

container.RegisterType(typeof(IApp), new InjectionFactory(f => App.Create(???, ???)));

What do I need to replace the '???' ?

More informations :

My Unity configuration is made in two phases. First phase (application is starting), I register all my object but one :

container.RegisterType<IOne, One>();
container.RegisterType<ITwo, Two>();
container.RegisterType<IApp, App>();
// ...

Phase two (user is logging), I juste register an instance of a context object who is used in constructor of all my classes (One, Two, App, ...) :

var childContainer = container.CreateChildContainer();
childContainer.RegisterInstance<AppEnvironment>(new AppEnvironment(userName));

This is my code without using InjectionFactory. It works fine. Now, I have to register multiple times my IApp interface, with calling a different static method each time. Example of static method :

public static IApp Create(IOne one, ITwo two, AppEnvironment env) 
{
    _one = one;
    _two = two;
    _env = env;
}

If I register IApp this this code :

container.Register(typeof(IApp), new InjectionFactory(f => App.Create(container.Resolve<IOne>(), container.Resolve<ITwo>(), container.Resolve<AppEnvironment>()));

Then my env variable is not set.

But if I register my env instance (just for test purpose, I can't do that in my case), it works.


Solution

  • Finally got the solution. It looks like willys one :

    container.RegisterType<IApp, App>(
        new InjectionFactory(
            f => App.Create(
                f.Resolve<IOne>(), 
                f.Resolve<ITwo>()
            )
        )
    );