如何使用Ninject与样本代码接口及其实现这样的:如何在Ninject中使用非默认的构造函数?
public interface IRepository
{
// common methods for all content types
void Insert(BaseContentObject o);
void Update(BaseContentObject o);
void Delete(string slug);
void Delete(ContentType contentType, string slug);
IEnumerable<BaseContentObject> GetInstances();
BaseContentObject GetInstance(ContentType contentType, string slug);
BaseContentObject GetInstance(string contentType, string slug);
BaseContentObject GetInstance(string slug);
IEnumerable<string> GetSlugsForContentType(int limit = 0, string query = "");
ContentList GetContentItems();
bool IsUniqueSlug(string slug);
string ObjectPersistanceFolder { get; set; }
}
public class XmlDefaultRepository : IRepository
{
private ContentType SelectedType;
public XmlDefaultRepository(string contentType)
{
SelectedType = (ContentType) Enum.Parse(typeof(ContentType), contentType);
}
public void Insert(Models.ContentClasses.BaseContentObject o)
{
throw new NotImplementedException();
}
// ...
}
public class PageController : BaseController
{
private IRepository ContentRepository { get; private set; }
public PageController(IRepository repository)
{
ContentRepository = repository;
}
//
// GET: /{slug}
// GET: /Pages/{slug}
public ActionResult Display(string slug)
{
// sample repository usage
Page page = ContentRepository.GetInstance(slug);
// ...
}
}
我的代码不包含默认构造函数,因为我并不需要一个(即使想创造它,我不能因为我总是要求的内容类型来提供。
我不能让一个默认的构造函数,因为没有逻辑上不提供默认的内容类型。
这是Ninject产生试图加载我的ASP当异常.NET MVC页面。
*Error activating string
No matching bindings are available, and the type is not self-bindable.
Activation path:
- Injection of dependency string into parameter contentType of constructor of type XmlDefaultRepository
- Injection of dependency IRepository into parameter repository of constructor of type PageController
- Request for IController
Suggestions:
- Ensure that you have defined a binding for string.
- If the binding was defined in a module, ensure that the module has been loaded into the kernel.
- Ensure you have not accidentally created more than one kernel.
- If you are using automatic module loading, ensure the search path and filters are correct.*
我已经更新了我的代码是肯定。并提供Ninject的例外 – mare 2010-07-06 12:56:08
如果我继续上面的代码,并在我的Ninject模块中执行此操作 绑定().To ()。WithConstructorArgument(“contentType”,“Page”); 然后它工作,但是事情是,我无法将我的contentType构造函数参数绑定到我的Module中的“Page”中,这个构造函数参数与控制器有关,所以在我的PageController中,XmlDefaultRepository会使用contentType的“Page”值实例化,但在其他控制器(如ServiceController)中,“contentType”参数值应等于“Service”。 –
mare
2010-07-06 14:25:52
希望你明白我不能硬编码模块中“contentType”参数的值。我怎么解决这个问题?控制器工厂等等是什么? – mare 2010-07-06 14:27:18