我正在尝试使用 Autofac 创建一个“生成”工厂,它将根据枚举参数实时解决依赖关系。
给定以下接口/类:
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 注册:
- Named
- Keyed
- Metadata
我找不到允许我定义生成的工厂委托的正确注册组合,该委托将返回正确的连接对象(对于 ConnectionType.Ssh 为 SshConnection,对于 ConnectionType.Telnet 为 TelnetConnection)。
更新Engine
上课Func<ConnectionType, IConnection>
而不是代表。奥特法支持通过以下方式动态创建委托工厂Func<T> http://docs.autofac.org/en/latest/advanced/delegate-factories.html.
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>();
如果连接本身需要依赖项,您可以调用Resolve
on the c
参数从当前调用上下文解析它。例如,new SshConnection(c.Resolve<IDependency>())
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)