Last active
December 28, 2015 21:19
-
-
Save makomweb/7563479 to your computer and use it in GitHub Desktop.
In case you have multiple constructors and you still want to take benefit of IoC you should not step into the trap of annotating your preferred constructor, because this makes your library code depend on a specific container implementation. Instead you should search for an alternative approach. Here it is: e.g. Unity's InjectionFactory.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FeatureService | |
{ | |
public FeatureService(string accessToken) | |
{ | |
// .. ommited internals | |
} | |
[InjectionConstructor] // <-- This annotation makes you depend on the IoC container's implementation! | |
public FeatureService(IFeatureDependency dependency) | |
{ | |
// .. ommited internals | |
} | |
} | |
public void AtSomeFunction() | |
{ | |
var container = new UnityContainer(); | |
var service = container.Resolve<FeatureService>(); | |
} | |
// ------------------------- or like this --------------------- | |
public class FeatureService | |
{ | |
public FeatureService(string accessToken) | |
{ | |
} | |
public FeatureService(IFeatureDependency dependency) | |
{ | |
} | |
// .. ommited internals | |
} | |
void AtSomeFunction() | |
{ | |
var container = new UnityContainer(); | |
container.RegisterType<FeatureService>(new InjectionFactory(_ => new FeatureService("token"))); | |
// Or, if you want the container to use the other constructor (it can even be used to resolve the dependency). | |
container.RegisterType<FeatureService>(new InjectionFactory(c => new FeatureService(c.Resolve<IFeatureDependency>()))); | |
var service = container.Resolve<FeatureService>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment