Question

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.

Was it helpful?

Solution 2

You can register it something like this.

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

OTHER TIPS

I am the author of LightInject and I can tell you that in the case where you actually pass inn arguments during the service request, it does not really make sense with any other lifetime besides the transient lifetime.

Since you have created a service that requires resolve-time arguments, you probably want a new instance of your service.

For services that does not require resolve-time arguments, you can do the combination of a factory delegate and the desired lifetime.

Hope this helps

Best regards

Bernhard Richter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top