使用 Ninject 在类中注入字符串属性

Har*_*hah 3 c# asp.net-mvc dependency-injection

我的一个接口有一个字符串属性,该属性取决于接口的使用位置。我想避免每次创建对象时对属性进行硬编码。我可以在构造函数中设置属性,但对象是使用工厂注入的。界面如下:

public interface IObjectStore
{
    string StorageTableName { get; set;}

    void UpdateObjectStore(string key, string value);

    string ReadObjectStore(string key);
}
Run Code Online (Sandbox Code Playgroud)

哪个在服务中使用

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
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

服务是使用服务工厂(Ninject.Extensions.Factory)创建的

 public interface IServiceFactory
{
    ICategoryService<T> CreateCategoryService<T>() where T : class;
}
Run Code Online (Sandbox Code Playgroud)

然后在控制器级别使用 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);
Run Code Online (Sandbox Code Playgroud)

所以问题是:我如何告诉 Ninject 每次将对象注入 CategoryService 时将属性 StorageTableName 设置为“CategoryTable”,并在每次将其插入到 ArticleService 时将其设置为“ArticleTable”?

sQu*_*r3l 5

我想这就是你要找的。
这只是我刚刚做的一个非常小的示例项目,但这应该可以解决您的问题。

public class Ninject_34091099
{
    public static void Run()
    {
        using (IKernel kernel = new StandardKernel())
        {
            kernel.Bind<IInterface<Generic1>>()
                  .To<Class<Generic1>>()
                  .WithConstructorArgument("name", "STRING ONE");

            kernel.Bind<IInterface<Generic2>>()
                .To<Class<Generic2>>()
                .WithConstructorArgument("name", "The other string");

            kernel.Bind<IServiceFactory>().ToFactory().InSingletonScope();

            var factory = kernel.Get<IServiceFactory>();
            var c1 = factory.CreateInterface<Generic1>();
            var c2 = factory.CreateInterface<Generic2>();

            Console.WriteLine(c1.Name);
            Console.WriteLine(c2.Name);
        }

        Console.WriteLine("Done");
        Console.ReadLine();
    }
}

public interface IInterface<T> where T : class
{
    string Name { get; set; }
}

public class Generic1
{

}

public class Generic2
{

}

public class Class<T> : IInterface<T> where T : class
{
    public string Name { get; set; }

    public Class(string name)
    {
        Name = name;
    }
}

public interface IServiceFactory
{
    IInterface<T> CreateInterface<T>() where T : class;
}
Run Code Online (Sandbox Code Playgroud)

抱歉,这些名字没有任何意义:D
希望它有所帮助