C# 如何为我的场景实现Unity DI以动态加载类
我想根据变量中保存的国家代码,使用Unity DI容器动态加载我的类 我们的win应用程序有一个发货功能,我们使用由第三方公司(如UPS、FedEx和Purolator)开发的web服务 现在,我应该如何使用unity设计代码,以便根据存储在变量中的国家代码加载shipping类 假设这是我的示例或建议的类设计:C# 如何为我的场景实现Unity DI以动态加载类,c#,unity-container,C#,Unity Container,我想根据变量中保存的国家代码,使用Unity DI容器动态加载我的类 我们的win应用程序有一个发货功能,我们使用由第三方公司(如UPS、FedEx和Purolator)开发的web服务 现在,我应该如何使用unity设计代码,以便根据存储在变量中的国家代码加载shipping类 假设这是我的示例或建议的类设计: public interface IShip { string Ship(); } public class UPS : IShip
public interface IShip
{
string Ship();
}
public class UPS : IShip
{
public string Ship()
{
}
}
public class FedEX : IShip
{
public string Ship()
{
}
}
public class Purolator : IShip
{
public string Ship()
{
}
}
如何使用unity根据变量值加载类
如果GB
存储在变量中,我想加载UPS类并调用ship函数,该怎么办
假设FR
存储在一个变量中,我想加载UPS类并调用ship函数
假设US
存储在变量中,我想加载联邦快递类并调用ship函数
假设
CA
存储在变量中,我想加载Purolator类并调用ship函数?您可以按名称注册类,并根据您的条件解析它们:
container.RegisterType<IShip, UPS>("UPS");
container.RegisterType<IShip, FedEX>("FedEX");
container.RegisterType<IShip, Purolator>("Purolator");
public IShip GetShippment(string c)
{
if (c == "GB" || c == "FR")
return container.Resolve<IShip>("UPS");
if (c == "US")
return container.Resolve<IShip>("FedEX");
if (c == "CA")
return container.Resolve<IShip>("Purolator");
throw new NotImplementedException();
}
...
var shippment = GetShippment("CA");
shippment.Ship();
container.RegisterType(“UPS”);
集装箱登记类型(“联邦快递”);
容器注册器类型(“Purolator”);
公共IShip GetShipment(字符串c)
{
如果(c==“GB”| c==“FR”)
退回集装箱。解决(“UPS”);
如果(c=“美国”)
退回集装箱。解决(“联邦快递”);
如果(c==“CA”)
退回集装箱。解决(“Purolator”);
抛出新的NotImplementedException();
}
...
var Shipment=GetShipment(“CA”);
shipment.Ship();
你能展示一下IShip的消费代码吗?我的想法是类设计。代码未启动。我想知道如何使用unity DI,它根据运行时提供的国家代码动态加载类。类似。谢谢你的代码,但你没有展示如何调用正确的ship函数……。你会添加更多的代码来展示如何调用ship函数吗?thanks@Thomas只需调用方法Ship
我将测试您的代码并让您知道。非常感谢:)