问题
Using Autofac, I would like to register a component and specify for a specific dependency to be resolved to a named instance.
I found samples like the following using constructor injection which is almost what I want.
builder.Register(c => new ObjectContainer(ConnectionStrings.CustomerDB))
.As<IObjectContainer>()
.Named("CustomerObjectContainer");
builder.Register(c => new ObjectContainer(ConnectionStrings.FooDB))
.As<IObjectContainer>()
.Named("FooObjectContainer");
builder.Register(c => new CustomerRepository(
c.Resolve<IObjectContainer>("CustomerObjectContainer"));
builder.Register(c => new FooRepository(
c.Resolve<IObjectContainer>("FooObjectContainer"));
However, I need this with property injection and I don't want to specify all dependencies.
Something like:
builder.Register<CustomerRepository>().With<IObjectContainer>("CustomerObjectContainer");
builder.Register<FooRepository>().With<IObjectContainer>("FooObjectContainer");
The build up of all unspecified dependnecies should happen with unnamed instances.
Thanks, Alex
[ADDITION TO THE ANSWER FROM Danielg]
An overload to resolve by type for any property of that type.
public static IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> WithDependency<TLimit, TReflectionActivatorData, TStyle, TProperty>(
this IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> registration,
Func<IComponentContext, TProperty> valueProvider)
where TReflectionActivatorData : ReflectionActivatorData
{
return registration.WithProperty(new ResolvedParameter((p, c) =>
{
PropertyInfo prop;
return p.TryGetDeclaringProperty(out prop) &&
prop.PropertyType == typeof(TProperty);
},
(p, c) => valueProvider(c)));
}
回答1:
I don't think that autofac has a shorthand way of doing this yet, but it is possible with a little effort.
I've written an extension method that does this. Throw it in a static extension class and you should be fine. The extension also shows how to do this the long way.
public static IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> WithResolvedProperty<TLimit, TReflectionActivatorData, TStyle, TProperty>(
this IRegistrationBuilder<TLimit, TReflectionActivatorData, TStyle> registration,
string propertyName, Func<IComponentContext, TProperty> valueProvider)
where TReflectionActivatorData : ReflectionActivatorData
{
return registration.WithProperty(new ResolvedParameter((p, c) =>
{
PropertyInfo prop;
return p.TryGetDeclaringProperty(out prop) &&
prop.Name == propertyName;
},
(p, c) => valueProvider(c)));
}
Don't mind the super long method signature, autofac registrations are very verbose.
You can use the extension like this.
builder.RegisterType<Foo>()
.WithResolvedProperty("Bar", c => c.Resolve<IBar>());
来源:https://stackoverflow.com/questions/9710779/autofac-resolve-a-specific-dependency-to-a-named-instance