【发布时间】:2016-10-20 19:34:33
【问题描述】:
您好,在 Autofac 我可以这样做:
public class Service1_Client
{
private const string ServiceName = "Service1";
Func<string, RabitMqClient> _clientFunc;
public Service1_Client(Func<string, RabitMqClient> clientFunc)
{
_clientFunc = clientFunc;
}
public IList<object> GetData()
{
return _clientFunc(this.ServiceName).Get<IList<object>>();
}
}
public class Service2_Client
{
private const string ServiceName = "Service2";
Func<string, RabitMqClient> _clientFunc;
public Service2_Client(Func<string, RabitMqClient> clientFunc)
{
_clientFunc = clientFunc;
}
public IList<object> GetData()
{
return _clientFunc(this.ServiceName).Get<IList<object>>();
}
}
public class RabitMqClient
{
private IConnectionFactory _connectionFactory;
private string _baseServiceName;
public RabitMqClient(IConnectionFactory connectionFactory, string baseServiceName)
{
_connectionFactory = connectionFactory;
_baseServiceName = baseServiceName;
}
public TResult Get<TResult>()
{
string topicName = this.GetTopicName();
///Connect to the channel that uses the topic and ask for data...
}
private string GetTopicNAme()
{
/// this should be an algoritam for getting the topic from the speccified baseServiceName (I have omitted the details)
return this._baseServiceName;
}
}
现在解释: 基本上我有一个依赖于 2 个参数的类(RabitMqClient):
- connectionFactory (IConnectionFactory)
- baseServiceName(字符串)
这些参数用于连接到 RabbitMq 服务器。 现在我使用 RabbitMq 中的 Topics 来多样化服务,为了得到正确的 Topic,使用了字符串参数 baseServiceName。 调用方 (Service1_Client, Service2_Client) 应提供字符串参数 baseServiceName。
在 Autofac 我可以像这样注册这个类:
builder.Register((context, parameters) =>
{
var param = parameters.First() as Autofac.TypedParameter;
return new HcRabbitMqClient(
context.Resolve<IConnectionFactory>(),param.Value.ToString());
}).AsSelf().InstancePerDependency();
这告诉 Autofac,当请求这个类时,让 Autofac 解析第一个参数,但调用者将在调用站点提供第二个(字符串)参数。然后将这个字符串参数放入参数值中。 this的用法可以看上面的代码(Service1_Client,Service2_Client)GetData()方法;
如何在 StructureMap 中做到这一点?
【问题讨论】:
-
您能否提供更多关于如何在 Autofac 的应用程序中使用它的上下文?
标签: c# dependency-injection inversion-of-control instantiation structuremap