我正在使用Ninject 3和MVC WebAPI / Windows Azure项目遇到类似bug的问题。我有一个看起来像这样的存储库对象:
public class Repository : IRepository
{
/// <summary>
/// Initialize a new repository object.
/// </summary>
public Repository(
CloudStorageAccount storageAccount,
ISerializer serializer,
int timeoutMS = 30000,
string activityLogQueueName = "activitylog",
string fileStageName = "filestage",
string blobTrackingTableName = "blobtracking")
{
//snipped boring stuff
}
}
在NinjecWebCommon中我有这样的绑定:
kernel.Bind<Data.IRepository>().To<Data.Repository>();
kernel.Bind<Data.ISerializer>().To<Data.Serializer>();
kernel.Bind<Microsoft.WindowsAzure.Storage.CloudStorageAccount>().ToMethod((context) =>
{
//code to get storage account from azure config
}
在存储库初始化时,它使用activityLogQueueName等字符串来创建任何缺少的容器并设置Azure客户端对象。这一切都很好 - 问题是Ninject以某种方式获取第一个字符串参数(“activityLog”)的值并将其传递给所有字符串参数,因此我的blob容器和跟踪表最终也被命名为“activityLog”。
如果我在绑定中指定这些参数,如下所示:
kernel.Bind<Data.IRepository>().To<Data.Repository>().WithConstructorArgument("fileStageName", "filestage");
一切正常,所以我相信这不是我代码中的错误。
这是我正在使用的解析器:
public class NinjectResolver : NinjectScope, IDependencyResolver
{
private IKernel _kernel;
public NinjectResolver(IKernel kernel)
: base(kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectScope(_kernel.BeginBlock());
}
}
范围:
public class NinjectScope : IDependencyScope
{
protected IResolutionRoot resolutionRoot;
public NinjectScope(IResolutionRoot kernel)
{
resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).SingleOrDefault();
}
public IEnumerable<object> GetServices(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).ToList();
}
public void Dispose()
{
IDisposable disposable = (IDisposable)resolutionRoot;
if (disposable != null) disposable.Dispose();
resolutionRoot = null;
}
}
否则一切都是通过nuget传递的。