在C#/统一构造注入? [英] Constructor Injection in C#/Unity?

查看:307
本文介绍了在C#/统一构造注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C#与微软的统一框架。我不太知道如何解决这个问题。它可能有一些与我缺乏与统一的理解DI的。

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.

我的问题可以用下面的例子code来概括:

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");

当我呼吁总线的决心方法我怎么能肯定的是,人的儿子名为'蒂米注入和解决火车的时候我怎么能肯定那个人的爸爸与当时的名字'乔'解决?

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?

我在想,也许使用命名实例?但我无所适从。任何帮助将是AP preciated。

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#/统一构造注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆