Reputation: 437
I have a Keyed service registered in Autofac that I would like to be injected via the constructor. The service is registered
builder.Register((ctx, par) =>
{
var namedParameter = par.Named<string>("myNamedParameter");
... configuration and instantiation ...
}).Keyed<IMyService>(myKey);
and is currently being resolved explicitly
public class MyConsumer {
private readonly IMyService _myService;
//current
public MyConsumer(ILifetimeScope scope) {
_myService = _scope.ResolveKeyed<IMyService>(myKey, new NamedParameter("myNamedParameter", "parameterValue"));
}
//preferred
public MyConsumer(IMyService myService) {
_myService = myService;
}
}
However, I haven't been able to find a way to have said service injected during construction. Autofac's KeyFilterAttribute
only accepts a key; it doesn't appear to allow for NamedParameters
. Is this possible?
Upvotes: 0
Views: 967
Reputation: 16192
NamedService
is a specialized version of KeyedService
where the key is of type String
.
both
c.RegisterType<T>().Named<IT>("x");
c.RegisterType<T>().Keyed<IT>("x");
are equivalent.
You can use
public MyConsumer([KeyFilter("x")]IMyService myService) {
_myService = myService;
}
and it will resolve the service named "x"
of type IMyService
Upvotes: 2