首页 > 解决方案 > 如何在解析期间连接 Unity 以使用工厂方法?

问题描述

我正在学习 Unity 的诀窍,但我无法按照我想要的方式进行设置。

我已经建立了一个 MVCE 来说明它:

ACustomer有一个名字。

 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,它会是这样的:

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

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

标签: c#dependency-injectionunity-container

解决方案


解决工厂,创造你的客户。

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

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

两个额外的评论:

  • 如果您不是绝对需要,请避免直接使用容器。与其注入容器并调用 resolve 来获取工厂,不如先注入工厂。
  • 我个人喜欢使用接口,除非我 100% 确定我不需要它们。它们几乎没有成本,但使测试和扩展变得更加容易。唯一不会被接口的东西很可能是 DTO。

推荐阅读