Search code examples
c#.netsimple-injector

Generate Func<TParam1, TParam2, TService> factories in Simple Injector


I have some services registered in the container. And some type which has dependencies on this service and short living arguments. For example:

public class Foo
{
    public Foo(IService1 svc1, IService2 svc2, int entityId) { }
}

What I want to have is some way to auto generate factories for creating such objects without manually coding each factory. I can use Func<int, Foo> or create some IFooFactory (with CreateFoo(int entityId) method) and I want to let Simple Injector to auto generate implementation of this factory (in some generic way for any count of arguments).

Is it possible?


Solution

  • Take a look at the AutomaticParameterizedFactoryExtensionsTests class from the SimpleInjector github page. It has a test method that explains how to use the AutomaticParameterizedFactoryExtensions, which seems to be what you are asking for.

    This class is in the SimpleInjector.CodeSamples project in the source code.