使基于某些参数实现相同接口的 Autofac return 不同 类?
Making Autofac return different classes that implement same interface based on some parameter?
抱歉,如果之前有人回答过这个问题,但我进行了搜索,但没有找到我要找的东西,我不确定是因为这是一种不好的做法,还是因为我不知道合适的名字我正在寻找的东西。
我有这样的情况:我有一个邮件服务,它使用不同的提供商,具体取决于客户想要的提供商。客户可能希望通过 UPS、DHL、FedEx 或 USPost 发送邮件。他们每个人都将实现 IMailing
public interface IMailing
{
void Mail(string message);
}
public class UPS : IMailing
{
public void Mail(string message)
{
Console.WriteLine(message + ", mailed with UPS!");
}
}
public class DHL : IMailing
{
public void Mail(string message)
{
Console.WriteLine(message + ", mailed with DHL!");
}
}
...
我想根据一些参数得到IMailing的每个具体实现。比如说,一个字符串,我将传递给 Autofac,根据该字符串键,它将 return UPS、DHL、FedEx 等的实例。
有办法吗?可以吗?
谢谢。
您可以使用命名或键控服务。参见 Named and Keyed Services
注册
builder.RegisterType<UPS>().Named<IMailing>("ups");
builder.RegisterType<DHL>().Named<IMailing>("dhl");
检索
var r = lifeTimeScope.ResolveNamed<IMailing>("dhl");
或者,您可以将基于名称或键的查找注入到您的使用类型中,而不是注入 ILifeTimeScope
。
抱歉,如果之前有人回答过这个问题,但我进行了搜索,但没有找到我要找的东西,我不确定是因为这是一种不好的做法,还是因为我不知道合适的名字我正在寻找的东西。
我有这样的情况:我有一个邮件服务,它使用不同的提供商,具体取决于客户想要的提供商。客户可能希望通过 UPS、DHL、FedEx 或 USPost 发送邮件。他们每个人都将实现 IMailing
public interface IMailing
{
void Mail(string message);
}
public class UPS : IMailing
{
public void Mail(string message)
{
Console.WriteLine(message + ", mailed with UPS!");
}
}
public class DHL : IMailing
{
public void Mail(string message)
{
Console.WriteLine(message + ", mailed with DHL!");
}
}
...
我想根据一些参数得到IMailing的每个具体实现。比如说,一个字符串,我将传递给 Autofac,根据该字符串键,它将 return UPS、DHL、FedEx 等的实例。
有办法吗?可以吗?
谢谢。
您可以使用命名或键控服务。参见 Named and Keyed Services
注册
builder.RegisterType<UPS>().Named<IMailing>("ups");
builder.RegisterType<DHL>().Named<IMailing>("dhl");
检索
var r = lifeTimeScope.ResolveNamed<IMailing>("dhl");
或者,您可以将基于名称或键的查找注入到您的使用类型中,而不是注入 ILifeTimeScope
。