开发者

Dynamic runtime dependency injection

here's my开发者_如何学运维 situation:

I have an application that generates stuff based on templates (using T4) and i have multiple templates class that inherit from an ITemplate interface.

What i wanna do in my Main is to dinamically inject some ITemplate implementations in my Generator class, what implementation to use being read from a, let's say, configuration file. Then in the Main i should call the Generator that will understand what template to use and call the proper TransformText().

I'm using Ninject.

It's the first time i use Dependency Injection in a statically typed language, so I'm not sure on how to proceed...

Regards,

Hugo


If you are truly want to use DI here a simple example, but if you are searching something like plugin system you might wanna check out mef.

Lets assume you have a generator

public class Generator
{

   private ITemplate _template;
   public Generator(ITemplate t)
   {
      _template = t;

   }

   public void Generate()
   {
       _template.Generate();
   }
}

Setup your Modules.

public class MyNinjectModules : NinjectModule
    {
        public override void Load()
        {
            Bind<ITemplate>().To< TemplateImplementation>();
            Bind<Generator>().ToSelf();
    }
}

then prepare your Ninject Kernel, and use it.

public class Program
{
   public static void Main(
   {
      var kernel = new StandardKernel(MyNinjectModules);
      var myGenerator =    kernel.Get<Generator>();
   }


}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜