Search code examples
c#asp.net-mvcdependency-injectioninversion-of-controldryioc

DryIoC in class libraries


I have a rather simple solution setup:

Web Project --> Service layer --> Repositories

My IoCbootstrapper class is located in my web project.

var c = new Container();
c.Register<IUserService, UserService>();        
c.Register<ILoggingService, LoggingService>();

That's fine but my services are depending on repositories.

Is there a way to have a "parital bootsrapper" in Service layer class library that would then be somehow passed as a configuration to a web project since this way an instance of service cannot be created as web project is not aware of repositories?


Solution

  • Have service layer expose an action that takes the container and registers what is needed.

    Service layer which references Repositories

    namespace Project.ServiceLayer {
        public static class DryIocExtesnions {
            public static void AddServiceLayer(this IContainer c) {
                c.Register<IUserRepository, UserRepository>();        
                c.Register<IOtherRepository, OtherRepository>();
            }
        }
    }
    

    IoCbootstrapper located in web project.

    var c = new Container();
    c.Register<IUserService, UserService>();        
    c.Register<ILoggingService, LoggingService>();
    
    //Register service layer 
    c.AddServiceLayer();
    

    draw back, depending on your preference is that now the service layer has to be aware of concerns from the composition root. You could abstract the to your own container but that may be overkill.