这篇来自David Haydn的有用文章(编辑:删除了骗局链接,可能是本文)展示了如何使用InjectionConstructor
该类来帮助您使用Unity的装饰器模式来设置链.但是,如果装饰器链中的项目在其构造函数中具有其他参数,则InjectionConstructor
必须显式声明它们中的每一个(或者Unity将抱怨它找不到正确的构造函数).这意味着您不能简单地将新的构造函数参数添加到装饰器链中的项目,而无需更新Unity配置代码.
这里有一些示例代码来解释我的意思.所述ProductRepository
类首先被缠绕CachingProductRepository
,然后通过LoggingProductRepostiory
.除了在构造函数中使用IProductRepository之外,CachingProductRepository和LoggingProductRepository都需要来自容器的其他接口.
public class Product
{
public int Id;
public string Name;
}
public interface IDatabaseConnection { }
public interface ICacheProvider
{
object GetFromCache(string key);
void AddToCache(string key, object value);
}
public interface ILogger
{
void Log(string message, params object[] args);
}
public interface IProductRepository
{
Product GetById(int id);
}
class ProductRepository : IProductRepository
{
public ProductRepository(IDatabaseConnection db)
{
}
public Product GetById(int id)
{
return new …
Run Code Online (Sandbox Code Playgroud)