I have an application with client, Library and Interface as a middle layer. The classes in the Library implement the Interface.I want to call the library without having to reference it. So I dont have to do this:
IInterface myClass = new Library.MyClass();
One way is to use Unity I guess. Is there any other way? Somehow the whole idea of the Interface fades away right now.
Thanks
There are a couple of ways you can do this.
One, through the use of Dependency Inversion, as you show with Unity, and the other by writing class factories, and lastly, as you've mentioned, newing up the class instance, which is not really helpful at all :)
My own personal taste tends to Dependency Inversion, where Structuremap is my favourite IoC Container. Very easy to set up, and very easy to use, but most of the IoC Containers are very well documented.
The thing you typically end up with are something to the likes of:
IInterface myClass = myContainer.GetInstanceOf<IInterface>();
If I am right, the library is not a third party component and you can change the implementation!? If so, i would suggest to use MEF. It is part of the .Net framework and supports exactly what you want - loading components from other assemblies that are not necessarily referenced.
In your library, you have to declare the class to use in you app with an export attribute:
[Export(typeof(IInterface))] class MyClass : IInterface{ }
And in your client application, you can import the component with:
[Import(typeof(IInterface))] public IInterface myClase;
And finally you can compose all imports and exports:
var catalog = new AggregateCatalog();
// add assamby by type
catalog.Catalogs.Add(new AssemblyCatalog(typeof (AnyType).Assembly));
// add assembly by path
// this example adds all assembly in the current directory that ends with "Extension.dll".
catalog.Catalogs.Add(new DirectoryCatalog(#".", "*Extensions.dll"));
var container = new CompositionContainer(catalog);
// compose parts: MEF composes all imports and exports
container.ComposeParts(this);
It is usually being done by using Factory design pattern.
public interface IMyInterface
{
}
public class A : IMyInterface
{
internal A() // so, the user/developer won't be able to call "var a = new A()" outside of the scope of the assembly
{
}
}
public class B : IMyInterface
{
internal B()
{
}
}
public static class MyFactory
{
public static IMyInterface CreateA()
{
return new A();
}
public static IMyInterface CreateB()
{
return new B();
}
}
usage:
static void Main()
{
IMyInterface a = MyFactory.CreateA(); // instance of A
IMyInterface b = MyFactory.CreateB(); // instance of B
}
If you are creating an API, you can set the constructor of A and B to internal, so the developer won't be able to create an instance of them without using the Factory.
Note: you can use the factory to store the created instance, so it will return the same instance rather then creating a new one every single time.
Related
I understand this is only possible with a workaround. But why?
I want to add plugin support to my app. So I designed an abstract class that all future plugins will need to implement. Every plugin must implement a GetVersion() method like in this example code:
public abstract class Plugin
{
public abstract int GetVersion();
}
public class MyPlugin : Plugin
{
public override int GetVersion()
{
return 1;
}
}
This of course works perfectly as long as I instantiate the plugin before calling the GetVersion() method.
But if I want to get the version number of the plugin before creating an instance of it? To check compatibility for example?
public class Program
{
public Program()
{
if (MyPlugin.GetVersion() > 1)
{
PluginLoader.Load(new MyPlugin());
}
}
}
Although it might not answer directly your question "WHY" I think below solution might be usefull in your scenario:
Use assembly version attribute:
Assembly thisAssem = typeof(MyPlugin).Assembly;
AssemblyName thisAssemName = thisAssem.GetName();
Version ver = thisAssemName.Version;
It never can be done by C# because a static method cannot be implemented in derived classes.
Like the workaround, you can create a static factory to create the instance.
public abstract class Plugin
{
public abstract int GetVersion();
}
public class FactoryPlugin<T> where T : Plugin, new()
{
public static int GetVersion()
{
return new T().GetVersion();
}
}
public class Program
{
public Program()
{
if (FactoryPlugin<MyPlugin>.GetVersion() > 1)
{
}
}
}
Consider using the Factory pattern in a way similar to what a COM class factory does. You create two classes, your useful class, and a class factory class. Your class factory class implements IPluginFactory. You package it with your Plugin. The plugin factory has vary simple methods, but one of them allows your Plugin to be created. It's close to what #ThierryV showed, but without static methods. So the process is:
Use whatever you are planning to use to store and instantiate your plugins, but instead of instantiating a plugin, you instantiate the appropriate Plugin Factory
You can have the Plugin factory do what ever you want -- get detailed information about the plugin, allow instantiation of the latest version or a particular version of the plugin - go to town
But, eventually, you use an instance of the factory to instantiate your Plugin.
This is a good place to start: What exactly is a Class Factory?, but Don Box's Essential COM book is where I learned all this stuff, a long time ago in a place far away.
I'm trying to understand how to use TypedFactoryFacility to create an abstract factory, and I have it working at a basic level, however I don't fully understand how to scale it with runtime dependencies
Suppose I have a service that needs to be created at runtime:
public interface IRuntimeService {
void DoThing();
}
with the following implementation
public class RuntimeService : IRuntimeService {
public void DoThing() {
// Do some work
}
}
To create my IRuntimeService, I've created an abstract factory
public interface IRuntimeServiceFactory {
IRuntimeService CreateService();
}
In my Castle installer, I'm using the TypedFactoryFacility to register my class and abstract factory.
public class TypeInstaller : IWindsorInstaller {
public void Install(IWindsorContainer container, IConfigurationStore store) {
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<IRuntimeService>().ImplementedBy<RuntimeService>());
container.Register(Component.For<IRuntimeServiceFactory>().AsFactory());
}
Then in my class that will be using the service, I can use the factory to create new service instances at runtime.
var myService = m_ServiceFactory.CreateService();
Everything above works perfectly, however I'm running into a problem when my RuntimeService class needs to be injected with a dependency chain itself that include runtime parameters.
To expand the example above, suppose I have a new runtime dependency
public interface IRuntimeDependency {
void DoWork();
}
implemented by a class that takes a runtime string value through the constructor
public class RuntimeDependency : IRuntimeDependency {
private readonly string m_Param;
public RuntimeDependency(string param) {
m_Param = param;
}
public void DoWork() {
// Do work involving the param
}
}
And the previously defined service class now needs a reference to the dependency
public class RuntimeService : IRuntimeService {
private readonly IRuntimeDependency m_Dep;
public RuntimeService(IRuntimeDependency dep) {
m_Dep = dep;
}
public void DoThing() {
// Do some work involving the dependency
m_Dep.DoWork();
}
}
How do I now I create instances of my service using the TypedFactoryFacility?
I would expect do just be able to change my factory method to look like
IRuntimeService CreateService(string param);
but Windsor throws an error 'Could not resolve non-optional dependency for parameter 'param' type 'System.String'.
Windsor knows how to create an IRuntimeDependency if I give it a string, and it knows how to create a IRuntimeService if I give it the dependency, so why can't it directly create a IRuntimeService with the string param?
I can make it work by having two distinct factory methods
IRuntimeService CreateService(IRuntimeDependency dep);
IRuntimeDependency CreateDependency(string param);
and creating the dependency, manually myself
var dep = m_ServiceFactory.CreateDependency(param);
var myService = m_ServiceFactory.CreateService(dep );
^^^This works, but the whole point of using a container is so that it will take care of assembling new objects for me. This is a relatively simple example involving only one dependency, but it would easily grow out of control with a more complex object graph.
I could of course create my own factory implementations, but that also nullifies the benefit of using the TypedFactoryFacility which is supposed to create the abstract factory implementations for you. I have a hard time believing there's not an existing solution to this problem but the Windsor examples don't contain any chained run-time dependencies.
I don't think using a FactoryComponentSelector is the correct approach because there's only one possible path to create the RuntimeService instance. It should be able to auto-resolve.
In many or most cases, an object resolved by the container depends on implementations of other interfaces which are also resolved by the container. So as long as all of the interfaces have registered implementations, the container can resolve the entire dependency chain.
But in this case RuntimeDependency depends on a string, which isn't something the container can resolve.
public RuntimeDependency(string param) {
m_Param = param;
}
In this case you can use the DependsOn method to explicitly provide a value to fulfill that dependency.
container.Register(Component.For<IRuntimeDependency, RuntimeDependency>()
.DependsOn(Dependency.OnValue("param","whatEverTheValueIs")));
That value can, of course, come from configuration or wherever else. I use this a lot with SQL connection strings.
It is possible using DynamicParameters.
container.Register(Component.For<IRuntimeService>()
.ImplementedBy<RuntimeService>()
.LifestyleTransient()
.DynamicParameters((k, d) => {
d["dep"] = new RuntimeDependency((string)d["param"]);
}));
Keep in mind that the dictionary keys have to match the parameter names in the CreateService method and RuntimeService constructor.
Edit: You should also make it LifestyleTransient if you intend to create a new instance each time the factory method is called. (The default is singleton)
It seems that what I am asking for is not possible by design.
See this other SO answer.
https://stackoverflow.com/a/3905496/2029835
i have a class that uses a proxy class inside to call a service that provide data. of course if the method create the proxy inside there is a problem to test that class. do you think that the proxy should be given in the constructor even if it can be created inside without "knowing" ?
You should provide class dependencies to class via dependency injection (constructor, property, parameter). That makes your class testable and allows to mock all those dependencies.
UPDATE:
Inject service proxy:
class Foo
{
private IServiceProxy _serviceProxy;
public Foo(IServiceProxy _serviceProxy)
{
_serviceProxy = serviceProxy;
}
public void Bar()
{
var staff = _serviceProxy.GetStaff();
}
}
Btw consider to hide information about proxy from your class. E.g. implement by proxy same interface that actual service has and provide IService to your class.
UPDATE2 (gateway):
All our domain needs - to get some staff. So, we define interface:
interface IStaffService
{
Staff GetStaff();
}
Our domain class (your tested class uses only this interface and does not depend on web services, proxy creation and other infrastructure concerns).
Next create Gateway (see definition on Martin Fowler site) for your service:
public MyServiceProxyGateway : IStaffService
{
public Staff GetStaff()
{
var proxy = new YourProxyType();
proxy.X = value;
proxy.Y = value;
var response = proxy.CallActualServiceMethod();
Staff staff = new Staff();
staff.Value = response.Something;
return staff;
}
}
Your code now completely unaware about all this infrastructure communications. And you use handy interface GetStaff instead of CallActualServiceMethod.
Well, there's a difference between "the proxy class knows how to instantiate itself" and "the class knows how to instantiate the proxy class". The second makes unit testing alot harder(if not impossible) if you pack that knowledge inside.
I'd use dependency injection (either via a framework,constructor or property) to take that knowledge to the caller - and make it testable.
To test my proxy classes i normally give the target that should be proxied within the constructor. Thous giving me the possibility to give a stub object for testing.
public class MyProxy : IProxiedInterface
{
private IProxiedInterface _Target;
public MyProxy(IProxiedInterface target)
{
if(target == null)
throw new ArgumentNullException("target");
_Target = target;
}
// ToDo: Implement all functions from IProxiedInterface
// and delegate them to the target
public bool DoSomething()
{
return _Target.DoSomething();
}
}
I use MEF to map interface to implementation class as a way of DI. For example, I use the Import attribute for an interface, and Export for implementation class. My understanding is that the MEF framework will create the implementation class instances and hold them in MEF's container for use or auto-injection.
Some of my implementation classes implement IDispose interface. Since instances are created by MEF, I think I should let the MEF to call components' Dispose method if they are disposable when the MEF is out. For example, in my application, I hold a reference to the MEF's container. When the application terminates, I call the Dispose method of the container. The problem is that my components' Dispose is never called.
Here are some example codes about the import and export mapping:
[Import]
private IMyInterface IComponent1 { get; set; }
....
[Export]
private IMyInterface Component {
get {
var instance = new MyImplemetation();
....
return instance;
}
}
....
There many other import and export definitions for other mappings in the similar way. I construct mappings in this way so that the MEF has the knowledge of the relationships and the way how to create the mapped instances. Here are some codes in my application to load mappings by using AssemblyCatalog:
var catalog = new AggregateCatalog();
catalog.Add (new AssemblyCatalog(Assembly.GetExecutingAssembly());
var batch = new CompositionBatch();
batch.AddPart(catalog);
// MEF container has all the mappings
var container = new CompositionContainer(catalog);
....
// Get instance from container
var instance = container.GetExportedValue<IMyInterface>();
// my instance CTOR has a contructor with several other
// implementation instances injected by interface
// instance starts to do its job and coordinates others ...
instance.Start();
....
// Finally the job is done.
// Dispose the container explicitly there.
container.Dispose();
// But my components are never disposed
// this results some connections not being closed
// file streams not being closed...
Here the instance has many other components injected through CTOR by the MEF. Those components also contain other components which are injected by the MEF. The problem is that it is really hard to make decision when to dispose components since some instances are shared. If I called Dispose on one, this would cause others not being able to use it. As you can see in this picture, instances are created by the MEF and injected to my application classes. Each component should not have any knowledge of others, and it should use injected components to do the job.
I am not sure where/how I should instruct the MEF to call Dispose on components when the application terminates or the container is disposed? Should I call the Dispose on components? I don't think that is right since the MEF creates them and inject them into clients as required. The clients should not call their Dispose when finishing their jobs.
MEF does manage the lifetime of the components it creates. It looks like the problem in your example is that the object you want disposed is not actually created by MEF. Perhaps you want to do something like this:
public class ComponentExporter : IDisposable
{
private IMyInterface _component;
[Export]
public IMyInterface Component
{
get
{
if (_component != null)
{
_component = new MyImplementation();
// ...
}
return _component;
}
}
public void Dispose()
{
if (_component != null)
{
_component.Dispose();
}
}
}
ComponentExporter is the class actually created by MEF, and if it implements IDisposable then MEF will dispose it with the container. In this example ComponentExporter disposes the created component when it is dispose, which is likely what you want.
Of course it would be easier if you just put the export on the MyImplementation class directly. I assume you have some reason for not doing that, but this is how it would look:
[Export(typeof(IMyInterface))]
public class MyImplementation : IMyInterface, IDisposable
{
// ...
}
A few other notes on your code: You probably don't need to add the catalog to the container via the batch, unless you are importing it somewhere and modifying it from parts inside the container. And if you happen to be processing many requests and are concerned about performance, you should only create the AssemblyCatalog once, and then use the same one for all requests.
Daniel is right. I defined a relationships of Import and Export as properties in my mapping classes. I loaded them as ComposablePartCatalog to MEF's container so that MEF can magically fetches corresponding instances on fly. It is within the mapping classes that I have some codes to new instances. Therefore, I have to find a way to let MEF to call back to those mapping classes to dispose the created resources when MEF is out of a process.
I like Daniel's suggestion to introduce a class for my Export part. Since all my DI mappings are defined in the way of properties (getter and setters), I created a base class like this:
public class ComponentExporterBase: IDisposable {
private List<IDisposable> _list;
public ComponentExporterBase() {
_list = new List<IDisposable>();
}
protect void Add(IDisposable obj) {
_list.Add(obj);
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
foreach(var obj in _list) {
obj.Dispose();
}
_list.Clear();
}
}
public void Dispose() {
Dispose(true);
}
}
With this base class, my mapping classes will be able to let MEF to do the disposing job. For example, here is one example:
internal class MyDIMappingClass : ComponentExporterBase {
[Import]
private IDataReader _dataReader { get; set; }
[Export]
private IController {
get {
var reader = _dataReader;
var instance = new MyMainController(reader);
base.Add(instance);
return instance;
}
...
}
All my mapping classes are defined in the similar way, and they are much cleaner. The basic principle is that instances or resources which are created within a class should be disposed within the class, but not injected instances. In this way, I don't need to clean up any injected instances by MEF any more, as in this example:
public class MyMainController : IController {
private IDataReader _dataReader;
// dataReader is injected through CTOR
public MyMainControler(IDataReader dataReader) {
_dataReader = dataReader;
...
}
...
public void Dispose() {
// dispose only resources created in this class
// _dataReader is not disposed here or within the class!
...}
}
By the way, I like to use properties as my imports and exports since the attributes have nothing to do a class' business logic. In other many cases, some classes are from third parties and I don't have access to their source codes to mark them as export.
Bear with me, I'm new to NUnit. I come from the land of Rails, so some of this is new to me.
I have a line of code that looks like this:
var code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
I'm trying to mock it, like this (assume code is already initialized):
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
When I debug the test, getCodeByCodeNameAndType is returning null, instead of the expected code. What am I doing wrong?
NUnit version: 2.2.8
I'm sorry, but I've never used NUnit.Mocks - but I do have some experience with NMock and Moq [which, by the way, I highly recommend]. Typically, you use a mocking library to generate proxies for Interface definitions, and I presume NUnit.Mocks operates the same way.
Therefore, if you would like to mock your singleton, you will likely have to do the following,
a. Create an interface, say
// All methods you would like to mock from this class, should
// be members of this interface
public interface IWebSiteConfiguration
{
// Should match signature of method you are mocking
CodeType getCodeByCodeNameAndType (
string codeString,
CatalogType catalogType);
}
b. "Implement" interface
// You've already written the method, interface matches signature,
// should be as easy as slapping interface on class declaration
public class WebSiteConfiguration : IWebSiteConfiguration { }
c. Consume interface
alright, so step c. is where most of your work will be. Logically, if you are mocking your singleton, you are actually unit testing the consumer [which you have left out of your sample]. For c. simply add a parameter to the consumer's ctor, or add a publicly accessible property of Type 'IWebSiteConfiguration', and then internally, reference the instance member and invoke your methods against this new interface. Consider this,
was
public class MyClass
{
public MyClass () { }
public void DoSomething ()
{
// bad singleton! bad boy! static references are bad! you
// can't change them! convenient but bad!
code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType (
"some.string",
someCatalog)
}
}
becomes
public class MyClass
{
private readonly IWebSiteConfiguration _config = null;
// just so you don't break any other code, you can default
// to your static singleton on a default ctor
public MyClass () : this (WebSiteConfiguration.Instance) { }
// new constructor permits you to swap in any implementation
// including your mock!
public MyClass (IWebSiteConfiguration config)
{
_config = config;
}
public void DoSomething ()
{
// huzzah!
code = _config.getCodeByCodeNameAndType ("some.string", someCatalog)
}
}
In your unit test, create the mock, pass a reference of the mock to the consumer, and test the consumer.
[Test]
public void Test ()
{
IWebSiteConfiguration mockConfig = null;
// setup mock instance and expectation via
// NUnit.Mocks, NMock, or Moq
MyClass myClass = new MyClass (mockConfig);
myClass.DoSomething ();
// verify results
}
This also serves as a practical introduction to Dependency Injection [DI]. It's simply the practice of passing, or "injecting", references of services [eg your web site configuration class] to the consumer, rather than having the consumer invoke the service directly [eg via static singleton class].
Hope this helps :)
A DynamicMock creates a new object in-memory that represents the interface, or marshallable (inherits from MarshalByRef) class you want to mock.
Try this:
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
WebSiteConfiguration conf = (WebSiteConfiguration)_websiteConfigurationMock.MockInstance;
var x = conf.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
Note that the third line there will not work unless WebSiteConfiguration inherits from MarshalByRef.
What you typically do is mock an interface and get a new object that implements this interface, but behaves the way you've configured it to do, without having to go and make a concrete type for it, so I'm not entirely sure what you're doing is going to work unless you employ a better isolation framework, like TypeMock that can intercept calls to static methods/properties in existing objects.
Seems there is a kind of solution for this using reflection, or maybe I totally misunderstood this.
It is discussed here:
http://www.geekbeing.com/2010/05/23/how-to-unit-test-singleton-hack-in-c
Could it really works?
public class TestableSingleton : SingletonClass
{
public TestableSingleton ()
{
FieldInfo fieldInfo = typeof(SingletonClass)
.GetField("_instance",
BindingFlags.Static | BindingFlags.NonPublic);
fieldInfo.SetValue(Instance, this);
}
}
Project availabe on https://github.com/rbabreu/TestableSingleton
Actually I could not compile it on Visual Studio since the SingletonClass would have a private constructor. If someone get it to work would be great to avoid the overhead of adapter pattern.