简体   繁体   中英

Autofac resolve Generic type with constructor parameters at run time

I have a generic class Logger<TProvider> where TProvider : ILogProvider which I'd like to configure dependency injection for with Autofac.

This class also has a constructor:

public Logger(LogType loggerType)

Which is currently used like this:

var logger = new Logger<Log4NetLogProvider>(LogType.CMS);

I was wondering if this could be dependency injected or will that not be possible due to type/constructor parameter required?

I'm aware of the RegisterGeneric method, eg:

builder.RegisterGeneric(typeof(Logger<>)).AsSelf()

I was wondering how I can tell autofac which TProvider was passed in and also provide the constructor parameter LogType ? Or is this not a good candidate for DI?

You could try using the WithParameter extension when registering the type

//using named parameter
builder.RegisterGeneric(typeof(Logger<>))
    .AsSelf()
    .WithParameter("loggerType", LogType.CMS);

//OR - using typed parameter
builder.RegisterGeneric(typeof(Logger<>))
   .AsSelf()
   .WithParameter(new TypedParameter(typeof(LogType), LogType.CMS));

Reference Passing Parameters to Register

The way that I coped with your problem was the following:

I registered the Generic class as you have done it.

builder.RegisterGeneric(typeof(Logger<>));

After that I register it with a type like so:

 builder.RegisterType<Logger<TProvider>>()
                .As<ILogger<TProvider>>()
                .WithParameter("loggerType", LogType.CMS);

or you can do it with Typed parameter like so:

builder.RegisterType<Logger<TProvider>>()
                    .As<ILogger<TProvider>>()
                    .WithParameter(TypedParameter.From(LogType.CMS)));

With TProvider being replaced with the paramater ie

builder.RegisterType<Logger<LogProvider>>()
                        .As<ILogger<LogProvider>>()
                        .WithParameter(TypedParamater.From(LogType.CMS)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM