How can I get started with ASP.NET (5) Core and Castle Windsor for Dependency Injection?

后端 未结 3 1310
滥情空心
滥情空心 2021-02-05 12:34

Background:

I\'ve used Castle Windsor with Installers and Facilities according to the Castle Windsor tutorial with earlier versions of MVC (pre-6) and WebAPI.

3条回答
  •  北海茫月
    2021-02-05 13:07

    There is a lot going on in your question, and to be honest I don't understand all of it.

    However, there is a working Castle Windsor composition root in MvcSiteMapProvider that you are welcome reverse-engineer. Follow these steps to get a working composition root demo project for Windsor:

    1. Create a new MVC 5 project.
    2. Install MvcSiteMapProvider.MVC5.DI.Windsor.
    3. Analyze the following files for the basic structure:
      • /App_Start/DIConfig.cs
      • /App_Start/CompositionRoot.cs
      • /DI/InjectableControllerFactory.cs
      • /DI/Windsor/WindsorDependencyInjectionContainer.cs
      • /DI/Windsor/Installers/MvcInstaller.cs
      • /DI/Windsor/Installers/MvcSiteMapProviderInstaller.cs

    Once you have this working configuration, you can then refactor it and add to it to suit your application's needs.

    As I recall, there weren't any changes required to make the MVC 4 DI configuration work with MVC 5. So, the problem you are running into is most likely one of the following:

    • You are using a 3rd party DI component that is not compatible with MVC 5.
    • You are using DependencyResolver, and your configuration doesn't include the necessary code to resolve the dependencies of MVC 5.
    • You are using advanced features of Castle Windsor that we are not using, and have them misconfigured in some way.

    ControllerFactory vs DependencyResolver

    Do note that according to Dependency Injection in .NET by Mark Seemann (which I highly recommend), it is ill-advised to use IDependencyResolver with Castle Windsor because it guarantees resource leaks. In fact, this is probably the most compelling argument that he makes for his reasoning for declaring service locator as anti-pattern.

    The recommended approach is to use IControllerFactory as the integration point into MVC, which implements a ReleaseController method to solve this issue.

提交回复
热议问题