如何在解析过程中连接Unity以使用工厂方法?

时间:2018-08-28 13:46:55

标签: c# dependency-injection unity-container

我正在学习Unity的绳索,但无法按自己的方式进行设置。

我已经设置了MVCE,以进行说明:

Customer有一个名字。

 public interface ICustomer
    {
        string name { get; set; }
    }
    public class Customer : ICustomer
    {
        public string name { get; set; }
        public Customer(string name)
        {
            this.name = name;
        }
    }

为了构建Customer,已经创建了一个工厂:

public interface ICustomerFactory
{
    ICustomer Create(string name);
}

public class CustomerFactory
    :ICustomerFactory
{
    public ICustomer Create(string name)
    {
        return new Customer(name);
    }
}

主程序是

static void Main(string[] args)
{
    const string customerName = "foo";

    var container = new UnityContainer();
    container.RegisterType<ICustomerFactory, CustomerFactory>();

    container.Resolve<ICustomer> //I would like this to return a customer named "foo".
}

我希望它的工作方式:

  • 当Unity尝试解析ICustomer时,它将使用与之关联的工厂ICustomerFactory-> 这就是我要努力的地方。
  • ICustomerFactory然后解析为其具体实现,CustomerFactory,然后调用Create(customerName)

在没有Unity的情况下,它将类似于:

ICustomerFactory factory = new CustomerFactory();
ICustomer customer = factory.Create(customerName);

我一直在查看Unity文档,但是很难理解,并且很难取得进展。

1 个答案:

答案 0 :(得分:0)

解决工厂并创建客户。

var factory = container.Resolve<ICustomer>();
var customer = factory.Create(customerName);

依赖注入是关于不是新事物的东西...

另外两条评论:

  • 如果您并非绝对需要,请避免直接使用容器。最好不要将容器注入并叫出决心去工厂,而最好首先注入工厂。
  • 我个人喜欢使用界面,除非我100%确信不需要它们。它们几乎免费,但使测试和扩展变得非常容易。唯一不会被接口的是DTO。