2012-12-15 70 views
5

我正在使用Ninject和ASP.NET MVC 4.我正在使用存储库,并且想要执行构造函数注入以将存储库传递给其中一个控制器。Ninject:构造函数参数

这是我的仓库接口:

public interface IRepository<T> where T : TableServiceEntity 
{ 
    void Add(T item); 
    void Delete(T item); 
    void Update(T item); 
    IEnumerable<T> Find(params Specification<T>[] specifications); 
    IEnumerable<T> RetrieveAll(); 
    void SaveChanges(); 
} 

AzureTableStorageRepositoryIRepository<T>实现:

public class AzureTableRepository<T> : IRepository<T> where T : TableServiceEntity 
{ 
    private readonly string _tableName; 
    private readonly TableServiceContext _dataContext; 

    private CloudStorageAccount _storageAccount; 
    private CloudTableClient _tableClient; 

    public AzureTableRepository(string tableName) 
    { 
     // Create an instance of a Windows Azure Storage account 
     _storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString); 

     _tableClient = _storageAccount.CreateCloudTableClient(); 
     _tableClient.CreateTableIfNotExist(tableName); 
     _dataContext = _tableClient.GetDataServiceContext(); 
     _tableName = tableName; 
    } 

注意的tablename参数需要的,因为我使用的是通用的表存储库数据持久化到Azure上。

最后我有以下控制器。

public class CategoriesController : ApiController 
{ 
    static IRepository<Category> _repository; 

    public CategoriesController(IRepository<Category> repository) 
    { 
     if (repository == null) 
     { 
      throw new ArgumentNullException("repository"); 
     } 

     _repository = repository; 
    } 

现在我想注入一个存储库到控制器。所以我创建了一个包含绑定的模块:

/// <summary> 
/// Ninject module to handle dependency injection of repositories 
/// </summary> 
public class RepositoryNinjectModule : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind<IRepository<Category>>().To<AzureTableRepository<Category>>(); 
    } 
} 

模块的装载动作完成的NinjectWebCommon.cs

/// <summary> 
    /// Creates the kernel that will manage your application. 
    /// </summary> 
    /// <returns>The created kernel.</returns> 
    private static IKernel CreateKernel() 
    { 
     var kernel = new StandardKernel(); 
     kernel.Bind<Func<IKernel>>().ToMethod(ctx =>() => new Bootstrapper().Kernel); 
     kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); 

     RegisterServices(kernel); 
     return kernel; 
    } 

    /// <summary> 
    /// Load your modules or register your services here! 
    /// </summary> 
    /// <param name="kernel">The kernel.</param> 
    private static void RegisterServices(IKernel kernel) 
    { 
     // Load the module that contains the binding 
     kernel.Load(new RepositoryNinjectModule()); 

     // Set resolver needed to use Ninject with MVC4 Web API 
     GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel); 
    } 

DependencyResolver的形成是因为Ninject的DependencyResolver实现System.Web.Mvc.IDependencyResolver,这不能被分配到WebApi应用程序的GlobalConfiguration.Configuration

因此,所有这一切,Ninject部分实际上是在Controller中注入正确的类型,但Ninject无法在构造函数AzureTableRepository中注入tableName参数。

在这种情况下,我该如何做到这一点?我已经咨询了很多文章和ninject文档,看看我可以如何使用参数,但我似乎无法得到它的工作。

任何帮助,将不胜感激。

回答

10

我会使用的方法WithConstructorArgument()像...

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

库设计的其余部分可能是另外一个问题。恕我直言,这似乎是一个很大的不得不创建一个表或在ctor中做任何繁重的工作。

+0

我想我会从构造器中删除创建,因为在ctor中执行大量初始化确实不是一个好习惯。 Thx! –

0

与此同时,我一直在与提供商玩弄尝试和伎俩,它似乎工作。

我不知道这是好主意,或者如果它是矫枉过正,但这里是我做了什么: 我创建了一个通用的提供者类:

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

然后我实现了一个在AzureTableRepositoryProvider。 (T,以支持具有多个实体类型相同的存储库。)

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

通过使用此提供我可以在右边的表名传递存储库的工作。但对我来说,还有两个问题:

  1. 这是一个好的做法还是我们可以做的事情更简单?
  2. 在NinjectProvider类中,我有两个notImplementedException情况。我怎么解决这些问题?我使用了以下链接的示例代码,但由于提供程序是抽象的,代码没有创建方法的主体,因此不起作用...enter link description here