Does a simple injector have a way to register a factory instance in combination with a TypeFactoryContext?

I am working on a legacy codebase that is in serious need of a SOLID refactoring. We add a simple injector injection container to the mixture as a first step.

For one of the registrations I need something very similar to the RegisterConditional example for Log4Net, i.e.

container.RegisterConditional(
    typeof(ILogger),
    c => typeof(Logger<>).MakeGenericType(c.Consumer.ImplementationType),
    Lifestyle.Singleton,
    c => true);

      

The difference is that I want to insert an instance returned by a factory method that takes a c.Consumer.ImplementationType value as:

container.Register???(
    typeof(ILogger),
    c => LoggerProvider.GetLogger(c.Consumer.ImplementationType),
    Lifestyle.Transient);

      

Can this be done with a simple injector?

I have read the answer to a similar question , but this is not enough. The implementation type must be passed to the factory instance.

I am currently implementing Logger <TParent> and am using this in the RegisterConditional call:

public class Logger<TParent> : ILogger
{
    private readonly ILogger _decoratedLogger;

    public Logger()
    {
        _decoratedLogger = Logger.GetLogger(typeof(TParent));
    }
}

      

+3


source to share


1 answer


Can this be done with a simple injector?

Yes and no.



  • No , this is not supported with help RegisterConditional

    and because Simple Injector tries to redirect you to type registration so that it can inspect and diagnose the object graph as well as possible. The preferred way is to create a proxy class as described here . It mainly explains your current solution, but has Logger<T>

    which inherits from LogImp

    instead, as it leads to a simpler solution.

  • Yes it is possible, but you will have to fall back to using a custom IDependencyInjectionBehavior

    one as described here (example for Serilog, but it can be easily rewritten in log4net). The first method is preferred whenever possible.

+3


source







All Articles