【问题标题】:Inject a string property in a class using Ninject使用 Ninject 在类中注入字符串属性
【发布时间】: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


【解决方案1】:

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

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;
}

对不起,这些名字没有任何意义:D
希望对你有帮助

【讨论】:

  • 对!谢谢。我需要做一些更像 kernel.Bind>() .To>().WhenInjectedInto("CategoryService") .WithConstructorArgument("name", "STRING ONE");跨度>
猜你喜欢
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多