gpt4 book ai didi

c# - 如何在解析期间连接 Unity 以使用工厂方法?

转载 作者:太空宇宙 更新时间:2023-11-03 14:50:15 26 4
gpt4 key购买 nike

我正在学习 Unity 的基本原理,但我无法按照我想要的方式进行设置。

我已经设置了一个 MVCE,以说明它:

客户 有一个名字。

 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的文档,但是非常难懂,而且进展很吃力。

最佳答案

解析工厂并创建您的客户。

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

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

另外两条评论:

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

关于c# - 如何在解析期间连接 Unity 以使用工厂方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52059458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com