Castle Windsor: Auto-register types from one assembly that implement interfaces from another

后端 未结 2 1346
情书的邮戳
情书的邮戳 2020-12-14 23:05

I use Castle Windsor as my IoC container. I have an application that has a structure similar to the following:

  • MyApp.Services.dll
    • IEmployeeSer
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 23:48

    With AllTypes you can easily do this:

    From http://stw.castleproject.org/(S(nppam045y0sdncmbazr1ob55))/Windsor.Registering-components-by-conventions.ashx:

    Registering components one-by-one can be very repetitive job. Also remembering to register each new type you add can quickly lead to frustration. Fortunately, you don't have to do it, at least always. By using AllTypes entry class you can perform group registration of types based on some specified characteristics you specify.

    I think your registration would look like:

    AllTypes.FromAssembly(typeof(EmployeeService).Assembly)
        .BasedOn()
        .LifeStyle.Singleton
    

    If you implement a base type, like IService on your interfaces, you can register them all at once using the following construct:

    AllTypes.FromAssembly(typeof(EmployeeService).Assembly)
        .BasedOn()
        .WithService.FromInterface()
        .LifeStyle.Singleton
    

    For more examples, see the article. This has a very good description on what the possibilities are.

提交回复
热议问题