c# - Autofac and Keyed registrations - the proper behavior? -
the question rather basic, started use autofac , encountered issue autofac not work expected work. given "that's way works" understand logic behind such behavior. here basic code:
public interface x { } internal class : x { } class program { static void main(string[] args) { var builder = new containerbuilder(); builder.registertype<a>().keyed<x>("a"); ilifetimescope scope = builder.build(); try { var instance = scope.resolve<x>(); } catch (exception e) { console.writeline(e); throw; } } } the attempt resolve result in error (exception). why ? indeed did not asked resolve specific keyed , calling
var instance = scope.resolvekeyed<x>("a"); would work , resolve expected, if register
builder.registertype<a>().keyed<x>("a").as<x>(); but why not resolve if did not asked specific keyed ? mean logic expected - ask specific - resolve specific, if did not ask specific - resolve any/last registered .
so why behavior selected default.
services registered keyed service resolvable using key. if want resolve service without using key, has registered without 1 using .as<...>(). register components both if wish them resolve using key or default.
to use analogy, can have door 2 kinds of handles: 1 lock, or 1 without. if want open keyed door, need supply key. door without lock doesn't require key.
Comments
Post a Comment