gpt4 book ai didi

c# - Autofac - 如何创建带参数的生成工厂

转载 作者:可可西里 更新时间:2023-11-01 07:44:02 25 4
gpt4 key购买 nike

我正在尝试使用 Autofac 创建一个“生成的”工厂,它将根据枚举参数实时解析依赖关系。

给定以下接口(interface)/类:

public delegate IConnection ConnectionFactory(ConnectionType connectionType);

public enum ConnectionType
{
Telnet,
Ssh
}

public interface IConnection
{
bool Open();
}

public class SshConnection : ConnectionBase, IConnection
{
public bool Open()
{
return false;
}
}

public class TelnetConnection : ConnectionBase, IConnection
{
public bool Open()
{
return true;
}
}

public interface IEngine
{
string Process(ConnectionType connectionType);
}

public class Engine : IEngine
{
private ConnectionFactory _connectionFactory;

public Engine(ConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}

public string Process(ConnectionType connectionType)
{
var connection = _connectionFactory(connectionType);

return connection.Open().ToString();
}
}

我想使用 Autofac 生成某种工厂,该工厂具有接收一个参数的方法:ConnectionType 并返回正确的连接对象。

我从以下注册开始:

builder.RegisterType<AutoFacConcepts.Engine.Engine>()
.As<IEngine>()
.InstancePerDependency();

builder.RegisterType<SshConnection>()
.As<IConnection>();
builder.RegisterType<TelnetConnection>()
.As<IConnection>();

然后我继续使用不同选项的 TelnetConnection/SshConnection 注册:

  1. 已命名
  2. 键控
  3. 元数据

我找不到允许我定义生成的工厂委托(delegate)的正确注册组合,该委托(delegate)将返回正确的连接对象(ConnectionType.Ssh 的 SshConnection 和 ConnectionType.Telnet 的 TelnetConnection)。

最佳答案

更新Engine上课 Func<ConnectionType, IConnection>而不是代表。奥托法克 supports creating delegate factories on the fly via Func<T> .

public class Engine : IEngine
{
private Func<ConnectionType, IConnection> _connectionFactory;

public Engine(Func<ConnectionType, IConnection> connectionFactory)
{
_connectionFactory = connectionFactory;
}

public string Process(ConnectionType connectionType)
{
var connection = _connectionFactory(connectionType);

return connection.Open().ToString();
}
}

在您的注册中使用 lambda 获取参数并返回正确的 IConnection实例。

builder.Register<IConnection>((c, p) =>
{
var type = p.TypedAs<ConnectionType>();
switch (type)
{
case ConnectionType.Ssh:
return new SshConnection();
case ConnectionType.Telnet:
return new TelnetConnection();
default:
throw new ArgumentException("Invalid connection type");
}
})
.As<IConnection>();

如果连接本身需要依赖项,您可以调用 Resolvec 上参数从当前调用上下文中解析它。例如,new SshConnection(c.Resolve<IDependency>()) .

关于c# - Autofac - 如何创建带参数的生成工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33288872/

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