Search code examples
c#.netdependency-injectionasp.net-web-api2unity-container

How to register Dependencies by Names in Unity


I'm using unity to implement Dependency Injection in my .NET Web Api app. Here is the relevent part of my WebApiCongig

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            var container = new UnityContainer();
            AppDependancyRegistry.Register(container);
            config.DependencyResolver = new UnityResolver(container);

        }
    }

And here is my AppDependancyRegistry class

 public static class AppDependancyRegistry
        {
            public static void Register(UnityContainer container)
            {
                    container.RegisterType(typeof(IBaseRepository<>), typeof(BaseRepository<>));
                    //container.RegisterTypes( AllClasses.FromLoadedAssemblies(),  WithMappings.FromMatchingInterface, WithName.Default);

            }
        }

I have mapped the Generic Repositores but I couldnt get through with registering the Manager classes to its interfaces. I dont want to map every one of Manager classes Manaually.

I have commented the part I have done from all the research. I just want a confirmation, this is how I do it as I cant get my App running now without doing some more of stuff

My manager classes:interfaces looks like

DutyManager: IDutyManager
UserDetailManager:IUserDetailManager

etc. Thanks in Advance


Solution

  • I found the solution to this qn. Using Unity we can directly Map all classes to respecive Interfaces by using

    container.RegisterTypes( AllClasses.FromLoadedAssemblies(),  WithMappings.FromMatchingInterface, WithName.Default);
    

    Here, Unity maps by convention where they map like this

    DutyManager: IDutyManager
    UserDetailManager:IUserDetailManager