![](/img/trans.png)
[英]Is it possible to remove an existing registration from Autofac container builder?
[英]Is it possible to exclude a constructor from autofac registration?
如果我有以下类,是否可以从Autofac注册中排除复制构造函数?
public class A
{
public A() {}
public A(A other) { // copy constructor }
public A(int b) { // some other stuff }
}
基本上,我希望autofac解析默认构造函数,或者如果用户请求Func<int, A>
第三个构造函数。 我从不希望autofac解析复制构造函数。 这可能吗?
原因是当我尝试使用Autofac注入Func<A>
,它会导致循环依赖,因为Autofac正在尝试使用第二个构造函数(它认为它知道解决A的方法,但是解决A需要A)。
您可以实现自己的构造函数选择器 ,忽略您的第二个构造函数:
public class AConstructorSelector : IConstructorSelector
{
public ConstructorParameterBinding SelectConstructorBinding(ConstructorParameterBinding[] constructorBindings)
{
if (constructorBindings == null) throw new ArgumentNullException("constructorBindings");
if (constructorBindings.Length == 0) throw new ArgumentOutOfRangeException("constructorBindings");
if (constructorBindings.Length == 1)
return constructorBindings[0];
var withLength = constructorBindings
.Where(b => !b.TargetConstructor.GetParameters().Select(p => p.ParameterType).Contains(typeof(A)))
.Select(binding => new { Binding = binding, ConstructorParameterLength = binding.TargetConstructor.GetParameters().Length })
.ToArray();
var maxLength = withLength.Max(binding => binding.ConstructorParameterLength);
var maximal = withLength
.Where(binding => binding.ConstructorParameterLength == maxLength)
.Select(ctor => ctor.Binding)
.ToArray();
if (maximal.Length == 1)
return maximal[0];
throw new DependencyResolutionException("Unable to find constructor");
}
}
注册您的类时,请将其用作UsingConstructor
参数
var builder = new ContainerBuilder();
builder.RegisterType<A>().UsingConstructor(new AConstructorSelector());
看小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.