简体   繁体   中英

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

You will need, at some point, to register each of them. However, if you don't want to manually do each and every one of them, what you could "basically" do is, by reflection, load the assembly, iterate over every interface, check how many classes implement that interface, if there is only one, register the interface to that class as an unnamed registration.

Why unnamed? Well, named registration are useless unless you actually use the name in the registration, or in the ResolvedParameter constructor, and since you're not "hand crafting" the registrations, you wouldn't refer to them most likely.

Don't forget though that in your case, since the interface and the classes are generics, you'll need to check the ParameterType too.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM