StructureMap resolve dependency through injection instead of service location

后端 未结 4 765
孤城傲影
孤城傲影 2021-02-09 19:50

In my project I register many ISerializers implementations with the assembly scanner. FWIW this is the code that registers my ISerializers



        
4条回答
  •  -上瘾入骨i
    2021-02-09 20:49

    As far as I know, that's not really what the assembly scanning functionality is meant for. It's more useful when a single assembly has numerous implementations of different interfaces (eg. IRepository, IRepository, etc.). So, for example, when you're referencing your test assembly you're injecting test repositories, and when you're in production you're injecting Entity Framework repositories.

    In your case, it doesn't look like any of your examples are fully injecting dependencies. In other words, when you write

    ObjectFactory.GetNamedInstance("JsonSerializer");
    

    you still have a dependency on the Json serializer by virtue of hard-coding the string, and it wouldn't make sense for StructureMap to ever return some other kind of serializer from that call.

    I can't tell exactly what you mean to accomplish with StructureMap, but if you need to return a particular serializer depending on a certain set of runtime conditions, you could look into conditional construction.

    On the other hand, it doesn't really sound like a switch of that sort is what you're going for here, so you should definitely consider getting rid of it. After all, the above code is really no different from

    new JsonSerializer();
    

    StructureMap is a wonderful tool, but it's not necessary for every project.

    Good luck!

提交回复
热议问题