c# - Inject string parameter with specific value to all types -


given

interface ifoo ... class myclass1 : ifoo {     public myclass1(string id) ... }  class myclass2 : ifoo {     public myclass2(string id) ... } //new classes added 

when resolve classes:

unitycontainer container = ...; container.resolve(typethatimplementsifoo); 

then how can setup unitycontainer injects value "123" ctor parameter "string id" when resolving class implements ifoo?

you can if write custom builderstrategy override input parameter in constructor classes.

i wrote test classes simplifying. similar classes:

    public interface ifoo {}      public class myclass : ifoo     {         public string id;          public myclass(string id)         {             id = id;         }     }      public class myclass2 : ifoo     {         public string id;          public myclass2(string id)         {             id = id;         }     } 

they custom builderstrategy , custom unitycontainerextension:

    public class unityextension<tinterface> : unitycontainerextension     {         private readonly string _paramname;         private readonly object _paramvalue;          public unityextension(string paramname, object paramvalue)         {             _paramname = paramname;             _paramvalue = paramvalue;         }          protected override void initialize()         {             var strategy = new buildstrategy<tinterface>(_paramname, _paramvalue);             context.strategies.add(strategy, unitybuildstage.precreation);         }     }      public class buildstrategy<tinterface> : builderstrategy     {         private readonly string _paramname;         private readonly object _paramvalue;          public buildstrategy(string paramname, object paramvalue)         {             _paramname = paramname;             _paramvalue = paramvalue;         }          public override void prebuildup(ibuildercontext context)         {             if (typeof(tinterface).isassignablefrom(context.originalbuildkey.type))             {                 context.addresolveroverrides(new parameteroverride(_paramname, _paramvalue));             }         }     } 

you need custom unitycontainerextension, because cannot access collection of builderstrategy unitycontainer without reflection.

and need add extension unitycontainer , try resolve type want:

    var container = new unitycontainer();     container.addextension(new unityextension<ifoo>("id", "123"));      var class1 = container.resolve<myclass>();     var class2 = container.resolve<myclass2>();      // show 123     console.writeline(class1.id);        // show 123     console.writeline(class2.id); 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -