Ninject : Constructor parameter

后端 未结 2 1541
抹茶落季
抹茶落季 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: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 : 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 : Provider> where T : TableServiceEntity
    {
        protected override AzureTableRepository 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 azureTableRepository = new AzureTableRepository(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

提交回复
热议问题