如何使用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.*
答案 0 :(得分:3)
你不需要引入一个默认的ctor来取悦Ninject。
假设您正在使用V2,the semantics for how a constructor is chosen are detailed here
(顺便说一句,默认情况下,string
类型不会被视为可解析类型的OOTB,但您应该可以Bind
ContentType
To
某些内容并拥有该构造函数调用)。
如果以上都没有让您感动,请提供一个使用场景和/或详细说明您遇到的问题的例外情况。
编辑:目前我不清楚您肯定处于不应该向ConstructorArgument
添加WithConstructorArgument()
(可能通过Bind<T>()
IIRC)的情况言。