【发布时间】:2015-12-04 14:56:03
【问题描述】:
我的一个接口有一个字符串属性,该属性取决于接口的使用位置。我想避免每次创建对象时对属性进行硬编码。我可以在构造函数中设置属性,但对象是使用工厂注入的。 界面如下:
public interface IObjectStore
{
string StorageTableName { get; set;}
void UpdateObjectStore(string key, string value);
string ReadObjectStore(string key);
}
在服务中使用
public class CategoryService<T> : ICategoryService<T> where T : Company
{
private readonly IObjectStore objectStore;
public CategoryService(IObjectStore objStore)
{
this.objectStore = objStore;
objectStore.StorageTableName = "CategoryTable"; // I want to avoid this hard coding
}
...
}
服务是使用服务工厂(Ninject.Extensions.Factory)创建的
public interface IServiceFactory
{
ICategoryService<T> CreateCategoryService<T>() where T : class;
}
然后在控制器级别使用 Ninject 注入。这是我的绑定
bool storeInNoSql = true;
kernel.Bind<IServiceFactory>().ToFactory().InSingletonScope();
kernel.Bind<ICategoryService<Article>>().To<CategoryService<Article>>();
kernel.Bind<IObjectStore>().ToMethod(ctx => storeInNoSql ? ctx.Kernel.Get<ObjectStore>() : null);
所以问题是:我如何告诉 Ninject 在每次将对象注入 CategoryService 时将属性 StorageTableName 设置为“CategoryTable”,并在每次将其插入 ArticleService 时将属性设置为“ArticleTable”?
【问题讨论】:
标签: c# asp.net-mvc dependency-injection