我需要根据外部条件构建要在运行时解析的实例名称。
Unity 中是否有我可以用来执行此操作的扩展点,还是我应该使用工厂?
例如:
container.RegisterType<IStrategy, FooStrategy>("FooStrategy");
container.RegisterType<IStrategy, BarStrategy>("BarStrategy");
var foo = container.Resolve<IStrategy>(); // would like to extend here to select the correct type to resolve.
Assert.IsTrue(foo.GetType() == typeof (FooStrategy));
最佳答案
目前还不完全清楚您想使用什么作为要解决的实例的驱动数据——正如史蒂文所说,Unity 不能只是猜测..
我想你可以使用你的逻辑来解析名称,它看起来像这样(来自 MSDN);
// Create container and register types
IUnityContainer myContainer = new UnityContainer();
myContainer.RegisterType<IMyService, DataService>("Data");
myContainer.RegisterType<IMyService, LoggingService>("Logging");
// Retrieve an instance of each type
IMyService myDataService = myContainer.Resolve<IMyService>("Data");
IMyService myLoggingService = myContainer.Resolve<IMyService>("Logging");
如果您有更复杂的逻辑,您还可以使用自定义解析器。看这里:http://msdn.microsoft.com/en-us/library/ee250036(v=bts.10).aspx
关于c# - 我如何自定义 Unity 解析实例的方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21870243/