>In our vertical market VFP app, we use a data-driven abstract factory to instantiate all of our classes containing business logic. Basically, that means instead of using CreateObject("MyClass"), we use Factory("MyClassKey"). The factory looks up the class in a table, then instantiates and returns the object. An important benefit of the factory is that it allows us to substitute a custom class for the standard one. For example, if a client wants us to customize a calculation for them, we put it in a custom class, install it on their system, then use the factory to instantiate the custom class in place of the standard one.
>
>I'm wanting to implement something similar in C#. The customizations for a specific client would be compiled into a custom DLL. Then I need to instantiate the custom class in place of the standard one. I figure I could probably roll my own factory using reflection and whatnot. I wondered if there was already a standard solution to this problem. I've been learning about IoC containers, but I can't tell if they do what I need. I'm not sure I buy into all of the dependency injection stuff, but I would be willing to use an IoC container if it also met my need with customizations. Or maybe there is some other mechanism built into .NET to achieve what I need. Any suggestions?
As an alternative to IOC you could use a factory to create the required class (given assembly name and class as strings)e.g (could be split into separate assemblies)
namespace Actions
{
public interface IActions
{
bool GetResult();
}
public class Type1Action : IActions
{
public bool GetResult()
{
return true;
}
}
public class Type2Action : IActions
{
public bool GetResult()
{
return false;
}
}
}
Then, for example:
using Actions;
using System;
namespace ConsoleApplication1{
class Program
{
static void Main(string[] args)
{
TheFactory f = new TheFactory();
var a = f.GetAction("Actions","Actions.Type1Action");
var result = a.GetResult();
var b = f.GetAction("Actions", "Actions.Type2Action");
result = b.GetResult();
}
}
public class TheFactory
{
public IActions GetAction(string assembly,string actionName)
{
var instance = Activator.CreateInstance(assembly, actionName);
return (IActions) instance.Unwrap();
}
}
}