Ninject : Constructor parameter

后端 未结 2 1527
抹茶落季
抹茶落季 2021-01-01 03:45

I am using Ninject together with ASP.NET MVC 4. I am using repositories and want to do constructor injection to pass in the repository to one of the controllers.

Thi

相关标签:
2条回答
  • 2021-01-01 04:00

    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.

    0 讨论(0)
  • 2021-01-01 04:17

    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
    0 讨论(0)
提交回复
热议问题