Search code examples
c#-4.0inversion-of-controllight-inject

Specify lifetime when registering services in LightInject while passing constructor parameters?


Using LightInject, lets say that I have a service that I want registered with multiple constructor parameters, example:

container.Register<double, bool, string, IFoo<String>>(
    (factory, arg1, arg2, arg3) => new Foo<String>(arg1, arg2, arg3));

I'm struggling to figure out how to specify an ILifetime instance during registration. Using simple registration I could set ILifetime for a simple registration like so:

container.Register<IFoo, Foo>(new PerRequestLifeTime());

It seems as though all the Register methods that use a factory assume transient objects.

I could create another interface for the parameters and register that, but I'd rather not create something new for every single instance where I would use multiple params in a constructor.

So, how can I register a service with a factory and a lifetime?

I'll admit that I'm somewhat new to IoC/DI so this may just come from me misunderstanding how to properly achieve this task, I'm sure there is also another way to do this.


Solution

  • You can register it something like this.

    container.Register<IFoo<String>>(factory => new Foo<String>(arg1, arg2, arg3), new PerRequestLifeTime());