현재 인터페이스를 일반 매개 변수 (생성자에서 적용됨)로 가져오고로드 된 모든 어셈블리의 모든 유형에서 해당 인터페이스를 구현하는 인스턴스화 된 객체를 가져올 수 있도록 일반 인스턴스 팩토리를 만들려고합니다. 다음과 같이반사 구체화
현재 구현은 다음과 같습니다
public class InstantiationFactory<T>
{
protected Type Type { get; set; }
public InstantiationFactory()
{
this.Type = typeof(T);
if (!this.Type.IsInterface)
{
// is there a more descriptive exception to throw?
throw new ArgumentException(/* Crafty message */);
}
}
public IEnumerable<Type> GetLoadedTypes()
{
// this line of code found in other stack overflow questions
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(/* lambda to identify instantiable types which implement this interface */);
return types;
}
public IEnumerable<T> GetImplementations(IEnumerable<Type> types)
{
var implementations = types.Where(/* lambda to identify instantiable types which implement this interface */
.Select(x => CreateInstance(x));
return implementations;
}
public IEnumerable<T> GetLoadedImplementations()
{
var loadedTypes = GetLoadedTypes();
var implementations = GetImplementations(loadedTypes);
return implementations;
}
private T CreateInstance(Type type)
{
T instance = default(T);
var constructor = type.GetConstructor(Type.EmptyTypes);
if (/* valid to instantiate test */)
{
object constructed = constructor.Invoke(null);
instance = (T)constructed;
}
return instance;
}
}
내가 나중에 다시 내 공장의 코드를 단순화 할 수 있도록 내 CreateInstance(Type)
기능 확장 방법으로 구현이 나에게 유용 할 것 같습니다,하지만 난 할 수 그 확장 메서드에서 강력한 형식의 값을 반환하는 방법을 알아낼 수 없습니다.
public static class TypeExtensions
{
public object CreateInstance(this Type type)
{
var constructor = type.GetConstructor(Type.EmptyTypes);
return /* valid to instantiate test */ ? constructor.Invoke(null) : null;
}
}
이 확장 방법은 확장 유형의 인스턴스 당 서명을 만드는 것이 가능하다 :
는 난 그냥 객체를 반환 할 수 실현?
내 완벽한 코드는 CreateInstance()
에 호출의 결과를 주조하는 것을 피한다되는이 될 것입니다 :
Type type = typeof(MyParameterlessConstructorImplementingType);
MyParameterlessConstructorImplementingType usable = type.CreateInstance();
... 내 전화 –