问题描述
我将 C# 与 Microsoft 的 Unity 框架结合使用.我不太确定如何解决这个问题.这可能与我对 DI 与 Unity 缺乏了解有关.
I'm using C# with Microsoft's Unity framework. I'm not quite sure how to solve this problem. It probably has something to do with my lack of understanding DI with Unity.
可以使用以下示例代码来总结我的问题:
My problem can be summed up using the following example code:
class Train(Person p) { ... }
class Bus(Person p) { ... }
class Person(string name) { ... }
Person dad = new Person("joe");
Person son = new Person("timmy");
当我在 Bus 上调用 resolve 方法时,如何确定注入了名为 'timmy' 的 Person 'son' 以及在解析 Train 时如何确定名为 'joe' 的 Person 'dad'解决了吗?
When I call the resolve method on Bus how can I be sure that the Person 'son' with the name 'timmy' is injected and when resolving Train how can I be sure that Person 'dad' with then name 'joe' is resolved?
我在想也许使用命名实例?但我不知所措.任何帮助将不胜感激.
I'm thinking maybe use named instances? But I'm at a loss. Any help would be appreciated.
顺便说一句,我宁愿不创建 IPerson 界面.
As an aside, I would rather not create an IPerson interface.
推荐答案
解决此问题的一种方法是使用具有命名注册的注入构造函数.
One way to solve this would be to use an injection constructor with a named registration.
// Register timmy this way
Person son = new Person("Timmy");
container.RegisterInstance<Person>("son", son);
// OR register timmy this way
container.RegisterType<Person>("son", new InjectionConstructor("Timmy"));
// Either way, register bus this way.
container.RegisterType<Bus>(new InjectionConstructor(container.Resolve<Person>("son")));
// Repeat for Joe / Train
这篇关于C#/Unity 中的构造函数注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论