c# - How to automatically resolve named type in Autofac? -
in unity, can register named type this
using microsoft.practices.unity; var container = new unitycontainer(); container.registertype<ioutputservice, consoleoutputservice>("console"); container.registertype<ioutputservice, messageboxoutputservice>("messagebox"); container.registertype<icalculatorreplloop, calculatorreplloop>(); icalculatorreplloop loop = container.resolve<icalculatorreplloop>();
and auto resolve using attribute this
public class calculatorreplloop : icalculatorreplloop { public calculatorreplloop() {} [dependency("messagebox")] public ioutputservice outputservice { get; set; } }
i know how register named service in autofac
using autofac; using autofac.core; var builder = new containerbuilder(); builder.registertype<consoleoutputservice>().named<ioutputservice>("console"); builder.registertype<messageboxoutputservice>().named<ioutputservice>("messagebox"); builder.registertype<calculatorreplloop>().as<icalculatorreplloop>().singleinstance(); icontainer container = builder.build(); icalculatorreplloop loop = container.resolve<icalculatorreplloop>();
but how resolve inside calculatorreplloop class ?
look @ sample code , 1 of ways of auto resolve using autofac when share contract 2 implementations.
using system; using autofac; using autofac.features.indexed; namespace autofac { class program { static void main(string[] args) { var builder = new containerbuilder(); builder.registertype<onlinestate>().keyed<idevicestate>("online"); builder.registertype<offlinestate>().keyed<idevicestate>("offline"); builder.registertype<modem>().asimplementedinterfaces(); var container = builder.build(); var r = container.resolve<imodem>(); r.print(); } } public interface idevicestate { string get(); } public class onlinestate : idevicestate { public string get() { return "onlinestate"; } } public class offlinestate : idevicestate { public string get() { return "offlinestate"; } } public class modem : imodem { readonly iindex<string, idevicestate> _states; private readonly idevicestate _devicestate; public modem(iindex<string, idevicestate> states) { _states = states; _devicestate = _states["online"]; //_devicestate = _states["offline"]; } public void print() { console.writeline(_devicestate.get()); } } public interface imodem { void print(); } }
Comments
Post a Comment