Ich hab dir mal ein Sample für ne Class Factory gebaut.
der Aufruf geht über
var rule = ClassFactory<IUser>.CreateInstance();
IUser ist ein Interface in einem Projekt, User ist eine konkrete IUser Implementierung die wir zurückgeben möchten. In der App Config stehen dann die Full Type Names von IUser und User:
<appSettings>
<add
key = "Contracts.IUser"
value ="Logic.User, User"
/>
</appSettings>
So erreicht man lose Kopplung und du kannst zu deinem projekt eine neue User Implementierung hinzufügen und über dein XML File ranstecken, ohne dein ganzes Projekt neu kompilieren zu müssen. Du kannst einfach die DLL ersetzen.
Die Konfiguration steuert die app.config, das ganze nennt sich das Inversion of Control ;-)
public static class ClassFactory<T>
where T : class
{
private static readonly string TypeFullName = typeof(T).FullName;
private static string GetTypeNameFromConfig()
{
var typeName = ConfigurationManager.AppSettings[TypeFullName];
if (string.IsNullOrEmpty(typeName))
{
throw new ConfigurationErrorsException(
string.Concat(
"Configuration setting not found: ",
TypeFullName
)
);
}
return typeName;
}
public static T CreateInstance()
{
var settingName = GetTypeNameFromConfig();
return CreateInstanceByName(settingName);
}
public static T CreateInstanceByName(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
var type = Type.GetType(name);
if (type == null)
{
throw new TypeLoadException(
string.Concat("Type not found: ",name)
);
}
var instance = Activator.CreateInstance(type) as T;
if (instance == null)
{
throw new TypeLoadException(
string.Concat("Type does not implement ", TypeFullName)
);
}
return instance;
}
}