Ninject bind all classes implementing the same interface

孤者浪人 提交于 2019-12-23 06:58:39

问题


I have an interface class:

public interface IStartUpTask
{
    bool IsEnabled { get; }
    void Configure();
}

I have multimple classes implementing the same interface

One of the classes looks like this:

public class Log4NetStartUpTask : IStartUpTask
{
    public bool IsEnabled { get { return true; } }

    public void Configure()
    {
        string log4netConfigFilePath = ConfigurationManager.AppSettings["log4netConfigFilePath"];
        if (log4netConfigFilePath == null)
            throw new Exception("log4netConfigFilePath configuration is missing");

        if (File.Exists(log4netConfigFilePath) == false)
            throw new Exception("Log4Net configuration file was not found");

        log4net.Config.XmlConfigurator.Configure(
            new System.IO.FileInfo(log4netConfigFilePath));
    }
}

How can i tell Ninject that i want all the classes implementing the IStartUpTask to bind to themself automatically?

I found an example using StructureMap which does this, but i don't know how to do it in Ninject.

Scan(x => {
    x.AssemblyContainingType<IStartUpTask>();
    x.AddAllTypesOf<IStartUpTask>();
    x.WithDefaultConventions();
});

回答1:


How can i tell Ninject that i want all the classes implementing the IStartUpTask to bind to themself automatically?

First of all, let me tell you that Ninject binds all classes to themselves automatically. You do not need to do anything special for that.

Having said that, I understand that you might want the explicit binding if you want to change scope or attach names or metadata. In this case read-on.

I do not know if it is possible to do what you are after in vanilla ninject, but you can use ninject.extensions.conventions. Using this library you can write:

Kernel.Bind(x => 
    x.FromThisAssembly()
    .SelectAllClasses()
    .InheritedFrom<IStartUpTask>()
    .BindToSelf());



回答2:


you can call it explicit in your code:

...
Bind<IStartUpTask>().To<Log4NetStartUpTask>();
Bind<IStartUpTask>().To<SomeOtherStartUpTask>();
...

Use it in SomeClass

public class SomeClass
{
   private readonly List<IStartUpTask> startUpTaskList;

   public SomeClass(IEnumerable<IStartUpTask> startUpTaskList)
   {
      this.startUpTaskList = startUpTaskList;
   }

   foreach (var startUpTask in this.startUpTaskList)
   {
      ...
   }
}


来源:https://stackoverflow.com/questions/15290353/ninject-bind-all-classes-implementing-the-same-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!