Dependency Injection in WebAPI with Castle Windsor

前端 未结 3 919
渐次进展
渐次进展 2020-12-23 12:33

I want to implement Dependency Injection in WebApi application using Castle Windsor. I have following sample code -

Interface -

publ         


        
3条回答
  •  情话喂你
    2020-12-23 12:51

    I didn't work directly with Castle Windsor, but I believe the logic should be similar:

    Your WatchController ctor should look like this:

    public WatchController(IWatch watch) 
    {
        _watch = watch;
    }
    

    And this is where you inject the dependency.

    You should have the equivalent to a Locator in which you register your WatchController class, and tell it which watch it should receive depending on whatever you want ... design/runtime , day of the week, random number ... whatever works or whatever you need...

    The following code is from MVVM-Light, but should clarify the above paragraph:

    static ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
    
        // This will run in design mode, so all your VS design data will come from here
        if (ViewModelBase.IsInDesignModeStatic)
        {
            SimpleIoc.Default.Register();
        }
        // This will run REAL stuff, in runtime
        else
        {
            SimpleIoc.Default.Register();
        }
    
        // You register your classes, so the framework can do the injection for you
        SimpleIoc.Default.Register();
        ...
    }
    

提交回复
热议问题