c# - 如何在解析期间连接 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 尝试解决
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);
依赖注入是关于不是新的东西......
两个额外的评论:
- 如果您不是绝对需要,请避免直接使用容器。与其注入容器并调用 resolve 来获取工厂,不如先注入工厂。
- 我个人喜欢使用接口,除非我 100% 确定我不需要它们。它们几乎没有成本,但使测试和扩展变得更加容易。唯一不会被接口的东西很可能是 DTO。
推荐阅读
- javascript - 为什么当我滚动到顶部然后在我的 API 应用程序上返回但在网页上正常运行时,我的页面顶部按钮口吃/滞后/粘住?
- html - 制作多个时HTML超链接不起作用
- r - 根据条件仅将 R 中的某些行转换为绝对值
- android - 如何将笔画添加到材质按钮的底部?
- javascript - Javascript在页面加载时更新标签的href
- typescript - 类型'文章| null' 不可分配给类型 'void'
- python - 我如何使不和谐的机器人不区分大小写?不和谐.py
- javascript - pagination.js 在 webpack rails 中不起作用
- python - 在guizero应用程序中按下Enter键时如何调用函数?
- nand2tetris - 破解程序集:添加 R3、R1、R9,给出错误“预期表达式”