我正在使用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();
}
下AzureTableStorageRepository
是IRepository<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文档,看看我可以如何使用参数,但我似乎无法得到它的工作。
任何帮助,将不胜感激。
我想我会从构造器中删除创建,因为在ctor中执行大量初始化确实不是一个好习惯。 Thx! –