Ninject : Constructor parameter

独自空忆成欢 提交于 2019-11-30 09:54:31

I'd use the WithConstructorArgument() method like...

Bind<IRepository<Category>>().To<AzureTableRepository<Category>>()
    .WithConstructorArgument("tableName", "categories");

The rest of the repository design is probably another question. IMHO It seems like a big no no to create a table or do any heavy lifting in a ctor.

Meanwhile I have been playing around with Providers to try and do the trick and it seems to work.

I don't know if this is good idea or if it is overkill but here is what I have done: I have created a generic provider class:

public abstract class NinjectProvider<T> : IProvider
{
    public virtual Type Type { get; set; }
    protected abstract T CreateInstance(IContext context);

    public object Create(IContext context)
    {
        throw new NotImplementedException();
    }

    object IProvider.Create(IContext context)
    {
        throw new NotImplementedException();
    }

    Type IProvider.Type
    {
        get { throw new NotImplementedException(); }
    }
}

And then I implemented that one in the AzureTableRepositoryProvider. (T to support having the same repository for multiple entity types.)

public class AzureTableRepositoryProvider<T> : Provider<AzureTableRepository<T>> where T : TableServiceEntity
{
    protected override AzureTableRepository<T> CreateInstance(IContext context)
    {
        string tableName = "";

        if (typeof(T).Name == typeof(Category).Name)
        {
            // TODO Get the table names from a resource
            tableName = "categories";
        }
        // Here other types will be addedd as needed

        AzureTableRepository<T> azureTableRepository = new AzureTableRepository<T>(tableName);

        return azureTableRepository;
    }
}

By using this provider I can pass in the right table name for the repository to work with. But for me, two questions remain:

  1. Is this good practice or could we do things much simpler?
  2. In the NinjectProvider class I have two notImplementedException cases. How could I resolve these? I used sample code from the following link but that does not work as the Provider is abstract and the code does not have a body for the create method... enter link description here
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!