如何在Ninject中使用非默认构造函数?

时间:2010-07-05 12:54:28

标签: c# 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:

  1. Injection of dependency string into parameter contentType of constructor of type XmlDefaultRepository
  2. Injection of dependency IRepository into parameter repository of constructor of type PageController
  3. Request for IController

Suggestions:

  1. Ensure that you have defined a binding for string.
  2. If the binding was defined in a module, ensure that the module has been loaded into the kernel.
  3. Ensure you have not accidentally created more than one kernel.
  4. If you are using automatic module loading, ensure the search path and filters are correct.*

1 个答案:

答案 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)的情况言。

相关问题