gpt4 book ai didi

c# - 是否可以从 autofac 注册中排除构造函数?

转载 作者:太空狗 更新时间:2023-10-30 01:18:26 25 4
gpt4 key购买 nike

如果我有以下类,是否可以从 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 注入(inject) Func<A> ,它导致循环依赖,因为 Autofac 试图使用第二个构造函数(它认为它知道解析 A 的方法,但解析 A 的方法需要一个 A)。

最佳答案

您可以实现自己的 constructor selector忽略你的第二个构造函数:

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());

参见 fiddle

关于c# - 是否可以从 autofac 注册中排除构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27479112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com