Dependency property and constructor parameters with Unity - c#

Let's say in C# I have a class called A
public class A : IInterfaceA
{
[Dependency]
B _b;
}
Then in B class I have a constructor like this:
public class B
{
...
public B(string someParam) { ... }
...
}
Now, I register class A like this:
_unityContainer.RegisterType<IInterfaceA, A>("RegistrationA");
and to resolve the interface I do:
_unityContainer.Resolve<IInterfaceA>("RegistrationA", new ParameterOverride("someParam", "The param."));
Now I want to know if it is good practice to resolve the class and pass the parameters like this or I should do it another way.
Thanks a lot :)

First of all the code you posted does not work: in fact you're overriding the parameter of class A, while in your code the constructor with the parameter is B.
Generally speaking, using parameter override is not a good practice in my opinion (unless some very specifical context like a console application or a web service using an existing container but it's avoidable in most cases) for these reason:
Using Resolve looks like a Service locator: anti-pattern nowadays. You will find a lot of discussion googling about.
Using ParameterOverride means that the client (the caller of Resolve) knows exactly the type mapped in the container and wants that type initialized with a specific parameter. But this is just the opposite of inversion of control.
The best way is to use an abstract factory. You can add in your code and use a more flexible and SOLID abstract factory:
public interface BFactory {
B Create(string bparam);
}
public class BFactoryUnity : BFactory {
private IUnityContainer container;
public BFactoryUnity(IUnityContainer container) {
this.container = container;
}
public B Create(String bParam) {
var b = new B(bParam);
container.BuildUp(b);
return b;
}
}
So you can register:
_unityContainer.RegisterType<IInterfaceA, A>("RegistrationA")
.RegisterType<BFactory, BFactoryUnity>();
Now the client can resolve only the factory and use it:
var bFactory = _container.Resolve<BFactory>();
var b = bFactory.Create();
Now, in a big application you will need a lot of similar factories. To avoid the boilerplate code of abstract factories and implementations you can find in the web some implementation of automatic abstract factory extensions.

Related

How to resolve concrete classes in Unity Dependency Injection

I seem to be stumped on how to implemented the strategy pattern with a DI container.
I have a strategy interface:
public interface IUserCompaniesInviteStrategy
{
bool InviteUserToCompany(UserCompaniesInviteRequest userCompaniesInviteRequest);
}
and a couple of concrete classes:
public class ConcreteExistingUserInviteStrategy : IUserCompaniesInviteStrategy
public class ConcreteNewUserInviteStrategy : IUserCompaniesInviteStrategy
How do I wire up Unity with this?
container.RegisterType<IUserCompaniesInviteStrategy, ConcreteExistingUserInviteStrategy>();
container.RegisterType<IUserCompaniesInviteStrategy, ConcreteNewUserInviteStrategy>();
obviously doesn't work...
I tried:
container.RegisterType<IUserCompaniesInviteStrategy<ConcreteExistingUserInviteStrategy>, ConcreteExistingUserInviteStrategy>();
container.RegisterType<IUserCompaniesInviteStrategy<ConcreteNewUserInviteStrategy>, ConcreteNewUserInviteStrategy>();
with
public interface IUserCompaniesInviteStrategy<T>
That doesn't seem to work.
I think what I'd like to do here is use named types, so like:
container.RegisterType<IUserCompaniesInviteStrategy, ConcreteExistingUserInviteStrategy>("1");
container.RegisterType<IUserCompaniesInviteStrategy, ConcreteNewUserInviteStrategy>("2");
However, I have constructor injection setup and using container.resolve isn't a good option for me because of n-tier architecture and chaining dependencies I'd have to resolve.
How can I inject a named type into a constructor? Is there a better way to do what I'm trying to do? (Create an interface that resolves to two concrete strategies)
Update:
I took a look at With Unity how do I inject a named dependency into a constructor? . The accepted answer won't work because I don't have a dependency on Unity in my domain, nor do I want it. I tried the StrategyResolver, but I'm getting:
An error occurred when trying to create a controller of type 'UserController'. Make sure that the controller has a parameterless public constructor.
That is indicative of a DI problem.
The StrategyResolver and IStrategyResolver are the same as in the example:
public class StrategyResolver : IStrategyResolver
{
private IUnityContainer container;
public StrategyResolver(IUnityContainer unityContainer)
{
this.container = unityContainer;
}
public T Resolve<T>(string namedStrategy)
{
return this.container.Resolve<T>(namedStrategy);
}
}
public interface IStrategyResolver
{
T Resolve<T>(string namedStrategy);
}
My config:
container.RegisterType<IUserCompaniesInviteStrategy, ConcreteExistingUserInviteStrategy>("ExistingUser");
container.RegisterType<IUserCompaniesInviteStrategy, ConcreteNewUserInviteStrategy>("NewUser");
container.RegisterType<IStrategyResolver, StrategyResolver>();
container.RegisterType<IUserFactory, UserFactory>();
Concretes:
public class ConcreteExistingUserInviteStrategy : IUserCompaniesInviteStrategy
public class ConcreteNewUserInviteStrategy : IUserCompaniesInviteStrategy
And then I call it like:
_strategyResolver.Resolve<IUserCompaniesInviteStrategy>("ExistingUser");
Not sure what's wrong with it.

Facade with two services inside and dependency injection - design pattern approach

I want to create Facade class to handle few operations on two services.
For contacting those services I've got proxy classes.
Having abstract Proxy and derived proxy per service - how can I create this part of architecture, to avoid Resolving in Facade?
class Facade
{
private Proxy proxy1;
private Proxy proxy2;
public Facade()
{
//I don't like this part
proxy1 = ...Resolve<Proxy1Type>();
proxy2 = ...Resolve<Proxy2Type>();
}
public void Do()
{
proxy1.Call();
proxy2.Call();
}
}
abstract class Proxy {public void Call();}
class Proxy1Type : Proxy {public void override Call(){}}
class Proxy2Type : Proxy {public void override Call(){}}
What design pattern should I use to fix this case?
EDIT
Optionally I should go in this solution, but still don't like it much
class Facade
{
private IProxy proxy1;
private IProxy proxy2;
//I feel it's still wrong
public Facade(IProxy1Type p1, IProxy2Type p2)
{
proxy1 = p1;
proxy2 = p2;
}
public void Do()
{
proxy1.Call();
proxy2.Call();
}
}
interface IProxy { void Call();}
interface IProxy1Type : IProxy{}
interface IProxy2Type : IProxy {}
class Proxy1Type : IProxy1Type { public void Call() { } }
class Proxy2Type : IProxy2Type { public void Call() { } }
There are two opposite approaches and you shown them both in the question. You can either resolve dependencies inside a class using Service Locator (first sample) or inject them from the outside using Dependency Injection.
Dependency Injection (constructor injection in your case) has a few advantages:
It's more clear what is needed for the Facade class to operate properly, since you do not need to dig inside the class to figure out what it'll try to resolve (and when).
It's easier to unit test the Facade class, since you're able to inject test doubles via constructor; there is no need to configure a DI container in the unit tests.
You can read more about Service Locator (and why you should avoid using it) in this post.

IoC and the Factory Pattern

If I understand the Factory Pattern correctly, I might have a factory for creating my Repos that implements an interface like this ...
public interface IRepoFactory
{
T Get<T>() where T : IRepo
}
And in that factory a call to RepoFactory.Get<IRepo1>() will return a newly minted instance of a class implementing IRepo1.
So, in the definition of RepoFactory I will create a new instance of the appropriate type...
switch(...)
{
case typeof(IRepo1):
return new Repo1();
}
Or, I assume, I can define a constructor for Repofactory that takes, as parameters, an interface representing all of the possible return types...
public RepoFactory(IRepo1 repo1, IRepo2 repo2, ..., IRepoN repoN) : IRepoFactory
and let my IoC container do the work of creating the classes.
So, to my question. If I do create a constructor as above, doesn't that mean that each time I include IRepoFactory as a constructor parameter I will get a new instance of Repo1, Repo2,..., RepoN? Is that a resource heavy process? Is it a wasteful way to do things if, in any given case, I will likely need only a subset of the total number of available repos?
Is there a way of getting the IoC (Unity, in my case) to only create an instance at the time it is needed, a Lazy Loading, if you will? Or am I simply worrying about nothing?
You misunderstood Factory. Factory should create instances. That's mean nothing should be in factory constructor beside of Di container or LifeTimeScope.
You can use your own factory or you can use auto generated factory.
I'm not familiar Unity but I checked they have.
public class MyService : IMyService
{
private readonly Func<IRepo1> _repo1;
public MyService(Func<IRepo1> repo1)
{
_repo1 = repo1;
}
public void Method1()
{
var myRepo = _repo1();
}
public void Method2()
{
//Repo1 instance will be different than in Method1
var myRepo = _repo1();
}
}
If you have a container then you can let the container resolve the type of repo when needed.
Here is a rough example of how you can do it. Note you will change the code to suit you specific container and also the assumption here is that you would have also already configured the container to know hot to resolve the types you want.
public class DefaultRepoFactory : IRepoFactory {
IUnityContainer container;
public DefaultRepoFactory(IUnityContainer container) {
this.container = container;
}
public T Get<T>() where T : IRepo {
return (T)container.Resolve<T>();
}
}
Configuration
IUnityContainer myContainer = new UnityContainer();
IRepoFactory myDefaultFactory = new DefaultRepoFactory(myContainer);
myContainer.RegisterInstance<IRepoFactory>(myDefaultFactory);

Simple Injector register multiple type of same interface with metadata

I have the following problem. I have one interface say IFoo and multiple implementations from it. Now, I have one web API controller, which according to some circumstances, should create a particular type of IFoo descendant, call it's method(s) and return result. The logic of the controller doesn't change no matter which implementation of IFoo I use. For this task, I need to tell the container which IFoo implementation to create from the controller, the problem is that, I don't know how to do that (if it's even possible with Simple Injector).
P.S. I already thought about RegisterAll, but in this case I'm forced to create all IFoo descendants (and pass it to the controller) when I need only one. This is not a solution for me.
Another solution would be to create different controllers for different IFoo implementations and use context based injection, but this will result in duplicated code/controllers that I want to avoid.
Ideally, the solution should be something like
container.RegisterAllWithMetadata(IEnumerable<Type> types, IEnumerable<string> metadata)
container.GetInstance(Type type, string metadata)
Is it possible to achieve my goal with Simple Injector?
sorry for bringing it back to life, but as it was said in the comments by Steven, your answer is in the docs
In situations where a service needs to create multiple instances of a certain dependencies, or needs to explicitly control the lifetime of such dependency, abstract factories can be used. Instead of injecting an IMyService, you should inject an IMyServiceFactory that creates new instances of IMyService:
// Definition
public interface IMyServiceFactory {
IMyService CreateNew();
}
// Implementation
sealed class ServiceFactory : IMyServiceFactory {
public IMyService CreateNew() {
return new MyServiceImpl();
}
}
// Registration
container.RegisterSingle<IMyServiceFactory, ServiceFactory>();
// Usage
public class MyService {
private readonly IMyServiceFactory factory;
public MyService(IMyServiceFactory factory) {
this.factory = factory;
}
public void SomeOperation() {
using (var service1 = this.factory.CreateNew()) {
// use service 1
}
using (var service2 = this.factory.CreateNew()) {
// use service 2
}
}
}

Auto-wiring property injection

I am trying to use property injection for StructureMap in a plug-in style system.
ObjectFactory.Initialize(o => o.Scan(s =>
{
s.AssembliesFromPath("path_to_assemblies");
s.WithDefaultConventions();
});
Here is a sample implementation (purposely did not go deeper in defining T and TU as they are just simple classes)
public interface IBarService
{
void Baz();
}
public class BarService : IBarService
{
public void Baz() { /* implementation */ }
}
public abstract class PluginBase<T, TU> : IPlugin
where T : AClass, new()
where TU : BClass
{
protected PluginBase()
{
//some init code in the constructor
}
}
//Foo is created at run-time via Activator.CreateInstance()
public class FooPlugin : PluginBase<AClass, BClass>
{
[SetterProperty]
public IBarService BarService { get; set; }
public void Fooey()
{
BarService.Baz();
}
}
I want to auto-wire the property dependencies on all of these plug-ins that are created at run-time. I thought I'd start out with property injection and then move things to the constructor if the need arose.
If I do:
var obj = ObjectFactory.GetInstance<IBarService>();
anywhere in an instance of FooPlugin, I get the correct implementation and all is well.
If I do:
this.BarService.Baz();
I get a null reference exception because no instance of IBarService was set.
After I create my plug-in, if I do this:
ObjectFactory.BuildUp(pluginObject).
All is well and FooPlugin has the correct implementation of IBarService.
Is there any way to simply allow me to decorate my plugin properties with [SetterProperty] and have StructureMap automatically inject those when the Plugin is created without having to call ObjectFactory.BuildUp(pluginObject) ?
How are you creating your plugin instance in the cases where it doesn't work? Are you just doing new FooPlugin()?
If you do var plugin = ObjectFactory.GetInstance<PluginBase<AClass, BClass>>();, do you get the plugin with all the correct dependencies resolved?
If you are instantiating the object with "new", the container has no way to know that the instance needs dependencies resolved--it has no knowledge of that instance. Instances that need injected dependencies must be "managed by the container" so to speak.
You'll save yourself a lot of trouble if you just go the opposite route and inject all dependencies in the contstructor(s). This way there is a single place where you need to check if your objects are initialized properly...

Categories