Reputation: 14618
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, e.g:
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?
Upvotes: 4
Views: 2230
Reputation: 370
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 i.e.
builder.RegisterType<Logger<LogProvider>>()
.As<ILogger<LogProvider>>()
.WithParameter(TypedParamater.From(LogType.CMS)));
Upvotes: 0
Reputation: 247018
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
Upvotes: 3