What if I don't need a special factory class and I want a concrete client to instantiate right parts. The client needs to call Hello() from that part. Everywhere else the focus is on making the factory method a method of a special creator class. But here it is right away in a client. Is this still a factory method pattern and is it even correct to use it as shown below?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
AClient c1 = new ClientUsingPart1();
c1.Foo();
AClient c2 = new ClientUsingPart2();
c2.Foo();
Console.ReadKey();
}
}
abstract class AClient
{
public AClient() { this.ipart = Create(); }
public void Foo() { ipart.Hello(); }
// many other methods
// ...
public abstract IPart Create(); // factory method
IPart ipart;
}
class ClientUsingPart1 : AClient
{
public override IPart Create() { return new Part1(); }
}
class ClientUsingPart2 : AClient
{
public override IPart Create() { return new Part2(); }
}
interface IPart
{
void Hello();
}
class Part1 : IPart
{
public void Hello() { Console.WriteLine("hello from part1"); }
}
class Part2 : IPart
{
public void Hello() { Console.WriteLine("hello from part2"); }
}
}
Depending on exactly what you need to achieve you should probably use some for of dependency injection with an IoC container of your choice; with StructureMap, Autofac, Unit, Ninject, Castle Windsor all very popular. Once you IoC container has built the concrete classes it should support a syntax like this
foreach (var client in Container.Resolve<IEnumerable<AClient>>())
{
client.Create();
}
You can read more about how to achieve this with StructureMap here: Does an abstract class work with StructureMap like an interface does?
According to this:
Differences between Abstract Factory Pattern and Factory Method
It seems the code I posted in the original post shows a valid use of the factory method pattern. The key is - factory method is just a method of the class - which also may be the sole client of the created objects.
Or in another way: factory method does not need to be public and provide the created objects to the outside world. In my example the Create() method should be protected.
Related
I`m confused about Dependency Injection implementation in one concrete example.
Let's say we have a SomeClass class that has a dependency of type IClassX.
public class SomeClass
{
public SomeClass(IClassX dependency){...}
}
Creation of concrete implementations of IClassX interface depends on runtime parameter N.
With given constructor, I can't configure DI container(Unity is used), because I don't know what implementation of IClassX will be used in runtime.
Mark Seemann in his book Dependency Injection In .Net suggests that we should use Abstract Factory as an injection parameter.
Now we have SomeAbstractFactory that returns implementations of IClassX based on runtime paramater runTimeParam.
public class SomeAbstractFactory
{
public SomeAbstractFactory(){ }
public IClassX GetStrategyFor(int runTimeParam)
{
switch(runTimeParam)
{
case 1: return new ClassX1();
case 2: return new ClassX2();
default : return new ClassDefault();
}
}
}
SomeClass now accepts ISomeAbstractFactory as an injection parameter:
public class SomeClass
{
public SomeClass(ISomeAbstractFactory someAbstractfactory){...}
}
And that's fine. We have only one composition root where we create the object graph. We configure Unity container to inject SomeAbstractFactory to SomeClass.
But, let's assume that classes ClassX1 and ClassX2 have their own dependencies:
public class ClassX1 : IClassX
{
public ClassX1(IClassA, IClassB) {...}
}
public class ClassX2 : IClassX
{
public ClassX2(IClassA, IClassC, IClassD) {...}
}
How to resolve IClassA, IClassB, IClassC and IClassD dependencies?
1. Injection through SomeAbstractFactory constructor
We can inject concrete implementations of IClassA, IClassB, IClassC and IClassD to SomeAbstractFactory like this:
public class SomeAbstractFactory
{
public SomeAbstractFactory(IClassA classA, IClassB classB, IClassC classC, IClassD classD)
{...}
...
}
Unity container would be used in the initial composition root and then use poor man’s DI to return concrete ClassX1 or ClassX2 based on parameter runTimeParam
public class SomeAbstractFactory
{
public SomeAbstractFactory(IClassA classA, IClassB classB, IClassC classC, IClassD classD){...}
public IClassX GetStrategyFor(int runTimeParam)
{
switch(runTimeParam)
{
case 1: return new ClassX1(classA, classB);
case 2: return new ClassX2(classA, classC, classD);
default : return new ClassDefault();
}
}
}
Problems with this approach:
SomeAbstractFactory knows about dependencies that don`t really belong to it.
Deeper object graph would require to change both SomeAbstractFactory constructor and class implementation
DI container would not be used to resolve dependencies, poor man`s DI must be used
2. Explicit call to DI container
Instead of “newing up” ClassX1 or ClassX2, we would resolve them by using a DI container.
public class SomeAbstractFactory
{
public SomeAbstractFactory(IUnityContainer container){...}
public IClassX GetStrategyFor(int runTimeParam)
{
switch(runTimeParam)
{
case 1: return container.Resolve<IClassX>("x1");
case 2: return container.Resolve<IClassX>("x2");
default : return container.Resolve<IClassX>("xdefault");
}
}
}
Problems with this approach:
DI container is passed into SomeAbstractFactory
DI Resolve method is not used only at the composition root (ServiceLocator anti-pattern)
Is there another more suitable approach?
The example below shows how to do this with Unity. This blog post explains it a little better using Windsor. The underlying concept is exactly the same for each, just slightly different implementation.
I would rather allow my abstract factory to access the container. I view the abstract factory as a way to prevent dependency on the container - my class only depends on IFactory, so it's only the implementation of the factory that uses the container. Castle Windsor goes a step further - you define the interface for the factory but Windsor provides the actual implementation. But it's a good sign that the same approach works in both cases and you don't have to change the factory interface.
In the approach below, what's necessary is that the class depending on the factory passes some argument that allows the factory to determine which instance to create. The factory is going to convert that to a string, and the container will match it with a named instance. This approach works with both Unity and Windsor.
Doing it this way the class depending on IFactory doesn't know that the factory is using a string value to find the correct type. In the Windsor example a class passes an Address object to the factory, and the factory uses that object to determine which address validator to use based on the address's country. No other class but the factory "knows" how the correct type is selected. That means that if you switch to a different container the only thing you have to change is the implementation of IFactory. Nothing that depends on IFactory has to change.
Here's sample code using Unity:
public interface IThingINeed
{}
public class ThingA : IThingINeed { }
public class ThingB : IThingINeed { }
public class ThingC : IThingINeed { }
public interface IThingINeedFactory
{
IThingINeed Create(ThingTypes thingType);
void Release(IThingINeed created);
}
public class ThingINeedFactory : IThingINeedFactory
{
private readonly IUnityContainer _container;
public ThingINeedFactory(IUnityContainer container)
{
_container = container;
}
public IThingINeed Create(ThingTypes thingType)
{
string dependencyName = "Thing" + thingType;
if(_container.IsRegistered<IThingINeed>(dependencyName))
{
return _container.Resolve<IThingINeed>(dependencyName);
}
return _container.Resolve<IThingINeed>();
}
public void Release(IThingINeed created)
{
_container.Teardown(created);
}
}
public class NeedsThing
{
private readonly IThingINeedFactory _factory;
public NeedsThing(IThingINeedFactory factory)
{
_factory = factory;
}
public string PerformSomeFunction(ThingTypes valueThatDeterminesTypeOfThing)
{
var thingINeed = _factory.Create(valueThatDeterminesTypeOfThing);
try
{
//This is just for demonstration purposes. The method
//returns the name of the type created by the factory
//so you can tell that the factory worked.
return thingINeed.GetType().Name;
}
finally
{
_factory.Release(thingINeed);
}
}
}
public enum ThingTypes
{
A, B, C, D
}
public class ContainerConfiguration
{
public void Configure(IUnityContainer container)
{
container.RegisterType<IThingINeedFactory,ThingINeedFactory>(new InjectionConstructor(container));
container.RegisterType<IThingINeed, ThingA>("ThingA");
container.RegisterType<IThingINeed, ThingB>("ThingB");
container.RegisterType<IThingINeed, ThingC>("ThingC");
container.RegisterType<IThingINeed, ThingC>();
}
}
Here's some unit tests. They show that the factory returns the correct type of IThingINeed after inspecting what was passed to its Create() function.
In this case (which may or may not be applicable) I also specified one type as a default. If nothing is registered with the container that exactly matches the requirement then it could return that default. That default could also be a null instance with no behavior. But all of that selection is in the factory and container configuration.
[TestClass]
public class UnitTest1
{
private IUnityContainer _container;
[TestInitialize]
public void InitializeTest()
{
_container = new UnityContainer();
var configurer = new ContainerConfiguration();
configurer.Configure(_container);
}
[TestCleanup]
public void CleanupTest()
{
_container.Dispose();
}
[TestMethod]
public void ThingINeedFactory_CreatesExpectedType()
{
var factory = _container.Resolve<IThingINeedFactory>();
var needsThing = new NeedsThing(factory);
var output = needsThing.PerformSomeFunction(ThingTypes.B);
Assert.AreEqual(output, typeof(ThingB).Name);
}
[TestMethod]
public void ThingINeedFactory_CreatesDefaultyTpe()
{
var factory = _container.Resolve<IThingINeedFactory>();
var needsThing = new NeedsThing(factory);
var output = needsThing.PerformSomeFunction(ThingTypes.D);
Assert.AreEqual(output, typeof(ThingC).Name);
}
}
This same factory can be implemented using Windsor, and the factory in the Windsor example could be done in Unity.
Hello first of all I'm just a newbie programmer, I just discovered how dependency injection pattern works and it is used to make my code more loosely coupled. I don't specifically know how to configure a Ninject to resolve the dependency, is it better to use these plug in?
Currently my approach when resolving dependency is like this.
public class MyClass
{
IContract _contract = null;
MyClass()
{
}
MyClass(IContract contract)
{
_contract = contract;
}
public void DoSomething()
{
IContract concreteImplementation = _contract ?? new ConcreteContract();
concreteImplementation.MyMethod();
}
}
public class ConcreteContract : IContract
{
public void MyMethod()
{
//do something;
}
}
public interface IContract
{
void MyMethod();
}
Edward...
I thought I'd add a little detail to my comment. The benefits of DI are as you mention (looser coupling). Also, it allows you to register your contract at both compile and runtime, depending on your requirement. As a result, you can add new implementations without breaking the class that you wish to resolve against.
You'll need a slight refactor to accomplish your goal using Unity. Below is a small self contained example (console app), using your class definitions (and showing an alternative implementation):
public class MyClass
{
readonly IContract _contract = null;
// do not include a paramterless ctor
// thus preventing class being created
// without a concrete implementation of IContract
public MyClass(IContract contract)
{
_contract = contract;
}
public void DoSomething()
{
_contract.MyMethod();
}
}
public class ConcreteContract : IContract
{
public ConcreteContract() { }
public void MyMethod()
{
//do something;
Debug.Print("Hello from the ConcreteContract class");
}
}
public class PlasticContract : IContract
{
public PlasticContract() { }
public void MyMethod()
{
//do something;
Debug.Print("Hello from the PlasticContract class");
}
}
public interface IContract
{
void MyMethod();
}
class Program
{
// add the nuget package Unity 1st
// Install-Package Unity
static void Main(string[] args)
{
// Declare a Unity Container -
// normally done once in the Startup/Bootstrap class
var unityContainer = new UnityContainer();
// Register IContract so when dependecy is detected
// it provides a ConcreteContract instance
// you could change this to <IContract, PlasticContract>
unityContainer.RegisterType<IContract, ConcreteContract>();
// Instance a MyClass class object through Unity
var preferredClass = unityContainer.Resolve<MyClass>();
preferredClass.DoSomething();
}
}
Hope this gets you to the next stage.
Code at bottom is from a working WPF sample application that used Autofac for dependency injection.
I want to convert to latest version of MEF instead. I also have NuGet packages CommonServiceLocator (V. 1.3) and Prism.Core, Prism.Mef and Prism.Wpf (all 6.1) installed.
When I do
var provider = ServiceLocator.Current.GetInstance<FriendDataProvider>();
I get an ActivationException from the "Func..." declaration in the constructor of FriendDataProvider.
Can MEF do this at all? If yes, what attribute declarations are required?
[Export]
public class FriendDataProvider
{
private readonly Func<IDataService> _dataServiceCreator;
[ImportingConstructor]
public FriendDataProvider(Func<IDataService> dataServiceCreator) // <= DI ERROR
{
_dataServiceCreator = dataServiceCreator;
}
public void DoSomething()
{
using (var service = _dataServiceCreator()) // Factory
{ }
}
}
[Export(typeof(IDataService))]
public class DataService : IDataService
{
public ClassA GetSomething()
{
return new ClassA();
}
public void Dispose()
{ }
}
public interface IDataService : IDisposable
{
ClassA GetSomething();
}
public class ClassA
{ }
Most likely you are looking for MEF ExportFactory class:
https://msdn.microsoft.com/en-us/library/ff382807(v=vs.110).aspx
It'a a mixture of Owned<> and Func<> ideas from AutoFac. Mind that ExportFactory.CreateExport returns ExportLifetimeContext which is Disposable. Disposing the export lifetime context will also dispose the injected part + all its dependencies. ExportFactory behavior is slightly different depending on Instancing mode of the owner part. If the owner class is a singleton ExportFactory will always create you new instance (behaves like Func< Owned< T>> in Autofac), but if you use it in combination with CompositionScopes you'll get behavior similar to Func< T> in AutoFac. See example: http://blogs.microsoft.co.il/bnaya/2013/01/16/mef-20-mini-series-part-6-composition-scoping-and-lifetime-management/
Here is your example re-written using ExportFactories:
[Export]
public class FriendDataProvider
{
private readonly ExportFactory<IDataService> _dataServiceCreator;
[ImportingConstructor]
public FriendDataProvider(ExportFactory<IDataService> dataServiceCreator) // <= DI ERROR
{
_dataServiceCreator = dataServiceCreator;
}
public void DoSomething()
{
using (var service = _dataServiceCreator.CreateExport()) // Factory
{
}
}
}
[Export(typeof(IDataService))]
public class DataService : IDataService
{
public ClassA GetSomething()
{
return new ClassA();
}
public void Dispose()
{ }
}
public interface IDataService : IDisposable
{
ClassA GetSomething();
}
public class ClassA
{ }
I have an assembly with a lot of classes (300+) with a BaseClass and I want register a generic class with a interface.
With unity you have to register by {Name} if you want to resolve an array of objects of the interface.
I want an array of objects in the MainViewModel automatically.
Is there a way to automate this with reflection?
Any suggestions?
Example (pseudo):
public class BaseClass
{
public void doFoo();
}
public ClassNumber001 : BaseClass
{
}
public ClassNumber002 : BaseClass
{
}
public interface ISuperman
{
}
public class Superman : ISuperman where T : BaseClass
{
}
public MainViewModel(IEnumerable<ISuperman> lotsofSuperman)
{
}
Working example by hand:
container.RegisterType<ISuperman, Superman <ClassNumber001>>("ClassNumber001");
container.RegisterType<ISuperman, Superman <ClassNumber002>>("ClassNumber002");
container.RegisterType<IEnumerable<ISuperman>, ISuperman[]>();
This is something that comes to my mind that might work for you...
You can register the type as follows, and should work for the open generic.
container.RegisterType(typeof(ISuperman<>), typeof(Superman<>), ... );
Registering generic parameters and types
Hope this helps!
Yes, you'll need to use reflection to easily create all of the mappings that you want. Since you are using Unity 3 you can take advantage of Registration by Convention to provide help (with the heavier lifting) in registering the classes.
I've taken your pseudo code and translated it into real code:
public abstract class BaseClass
{
public abstract void DoFoo();
}
public class ClassNumber001 : BaseClass
{
public override void DoFoo()
{
Console.WriteLine("001 Foo");
}
}
public class ClassNumber002 : BaseClass
{
public override void DoFoo()
{
Console.WriteLine("002 Foo");
}
}
public interface ISuperman
{
void Do();
}
public class Superman<T> : ISuperman where T : BaseClass
{
private T baseClass;
public Superman(T baseClass)
{
this.baseClass = baseClass;
}
public void Do()
{
this.baseClass.DoFoo();
}
}
public class MainViewModel
{
public MainViewModel(IEnumerable<ISuperman> lotsofSuperman)
{
foreach(ISuperman superman in lotsofSuperman)
{
superman.Do();
}
}
}
Then use registration by convention to register all the generics:
IUnityContainer container = new UnityContainer();
container.RegisterTypes(
AllClasses.FromAssembliesInBasePath().Where(t => typeof(BaseClass).IsAssignableFrom(t))
.Select(t => typeof(Superman<>).MakeGenericType(t)),
t => new Type[] { typeof(ISuperman) },
t => t.GetGenericArguments().First().Name,
WithLifetime.Transient);
container.RegisterType<IEnumerable<ISuperman>, ISuperman[]>();
container.Resolve<MainViewModel>();
In the above code we get all classes that inherit from BaseClass and then construct a type Superman<> and map that to ISuperman using the name of the BaseClass. The RegisterTypes call will be equivalent to calling RegisterType for every BaseClass:
container.RegisterType<ISuperman, Superman<ClassNumber001>("ClassNumber001");
container.RegisterType<ISuperman, Superman<ClassNumber002>("ClassNumber002");
Then when MainViewModel is resolved it iterates over all ISuperman instances and calls a method which prints out:
001 Foo
002 Foo
showing that we injected 2 ISuperman instances: Superman<ClassNumber001> and Superman<ClassNumber002>.
If you need specific registrations for the BaseClasses (e.g. non-default lifetime manager) then you can use registration by convention to register those too).
There are some of the ways this can be done. One is by using XML where the type is defined lets say MyClass and IMyClass and during runtime it resolves based on the assemblies available. But a better approach in my opinion would be to create a project to which you can delegate the responsibility of loading up the dependencies.
Lets say you create a class like so:
public class MyClass : IMyClass
{
private readonly IUnityContainer _container;
#ctor
// initialie the container through the constructor
public void DoWork<Interface, Class>() where Class: Interface
{
_container.RegisterType<Interface, Class>(
//TODO: You can setup the container lifecycle which can be transient
// or singleton or custom based on your project requirement
)
}
}
Now whoever needs to register itself can call this interface IMyClass to get itself registered in the container and dependency can be injected to whichever class needs to perform that task.
I have a class, which contain my actions (any logic):
public class socActions
{
public void Choose(int elem)
{
switch(elem) ... CalcA(elem) || CalcB(elem) ...
}
public void CalcA()
{
}
public void CalcB()
{
}
public void CalcC()
{
}
}
So, in my program, when i get elem value, i use it like:
(new socActions()).Choose(elem_val);
Okey, but in socActions class methods, i'd like to have a connection with my repository or make any other dependency injection.
If i add IRepositoryMy repositoryMy to constructor, then i couldn't
create classes as above, bcz its need now constructor with argument
IRepositoryMy.
If i try to make injection in field, it doesn't work
(property = null).
If i try to make injection in methods (CalcA,
CalcB) it doesn't work too.
How i really should make this task (inject class, for example repository)? Don't want to mark everything in my application as static :(
WinForms, C#, Ninject 3
Edit:
public class socActions
{
[Inject]
public IGridProcessor _GridProcessor { private get; set; }
so, in method its null:
public void UpdateInfo(...)
{
...
this._GridProcessor.Refresh();
}
In other classes, where i inject IGridProcessor to class in constructor, everything fine.
In Program.cs:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var kernel = new StandardKernel(new TwttModule());
var form = kernel.Get<Main>();
Application.Run(form);
}
public class TwttModule : NinjectModule
{
public override void Load()
{
Bind<IGridProcessor>().To<GridProcessor>();
}
}
public static class AnyClass
{
public static void Act()
{
....
(new socActions()).Choose(elem_val);
}
}
How should i inject IGridProcessor to socActions?
When using constructor injection, you don't construct your classes directly, but rather ask ninject for an instance. Based on how you've configured ninject, you get a new instance, or a singleton instance, etc.
From their docs:
Samurai warrior = kernel.Get<Samurai>();