c# - Autofac - resolving component with parameters dynamically -
I have a class that takes the interface as constructor logic. There are two implementations of this interface and I have to decide which implementation to use based on a variable runtime.
The problem is that the above class is deep in any object succession which is solved by autofak I can not pass in logic.
Something like lowering down what I'm trying to achieve. Public Interface IInterface1 {} Public Interface IInterface2 {} Public Class Class1: IInterface2 {Public Class1 (IInterface1 interface1) {}} Public Class Class2 {Public Class2 (IInterface2 interface2) {}} Public Category Class3 {Pure Zero GetClass2Instance (String interface1ImplementationToChoose) {// IInterface1 which is resolved based on the implementation is resolved Interface 1 Implementation Tutorial Variable var class2 = Container. Resolute & Lt; Class 2 & gt; (); Any ideas?
Update:
To clarify, this is an existing object hierarchy that is used by existing applications that work fine. In addition, the object model is much larger than the data shown in this example. Consequently, I really do not want to have a factory pass for every manufacturer in the graph graph that is used by a deep classroom in a graphic.
What is a different way of implementing Class II of IInterface1 passed in class1 without knowing anything about it?
Thanks
Yes, inject a factory that hides what type of type Selected: and then the container setup, with some of these lines: You can now use
Public class class 3 {Personal Func & lt; String, Class 2 & gt; _class2Factory; Public Class 3 (Funk & lt; String, Class 2 & gt; Class 2 Factor) {_class2Factory = class2Factory; } Public Zero GetClass2Instance (String Interface 1ImplementationToChoose) {var class2 = _class2Factory (interface1ImplementationToChoose); }}
builder.RegisterType & lt; Implementation1 & gt; () Name ("imp1") .. As the & lt; IInterface1 & gt; (); Builder.RegisterType & lt; Implementation2 & gt; () Name ("imp2") as the name & Lt ;. IInterface1 & gt; (); Builder.Register & lt; & Lt; String, class2 & gt; & Gt; (C = & gt; {var reference = c.Resolve & lt; IComponentContext & gt; (); Returned Imp => New Class2 (context.Resolve & lt; IInterface1 & gt; (IMP);}); Builder.RegisterType & lt; Class 3 & gt; ();
Class3
this way:
Public Class Class4 {Public Class4 (Class3 class3) {var Class2with1 = class3.GetClass2Instance ("imp1"); Var class2with2 = class3.GetClass2Instance ("imp2"); }} Note: I assume that you mean that
Class2
is injected with different implementations of the same interface Should be done IInterface1
. Your sample is a bit confusing because you are showing two classes implementing two interfaces.
Comments
Post a Comment