简体   繁体   中英

Registering multiple objects with same interface in Autofac

I'm calling the below code in XYZManager class's constructor and the application is working.

var handlers = new ITableType[]
{
    new AbcHandler(new Logger(), new Repository()),
    new OtherHandler(new Logger(), new Repository())
    /*etc...*/
};

XYZManager , Logger and Repository are registered in my application using Autofac.

The problem is I will have around 25 handlers when I go live and so would like very much a way to have a more maintainable code...

I hope I have been able to explain my problem.

EDIT: What I would like to know is how to register my handlers in autofac and what changes do I need to make to my above code..

I guess I could register every handler like this :

builder.RegisterType<AbcHandler>().As<ITableType>()

But how do I change my XYZManager class's constructor

After you register your implementors of ITableType , you can define your constructor like so...

public XYZManager(ITableType[] handlers, /* other params... */)
{

}

and Autofac will give you an array with one of each of your registered ITableType objects.

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