Ok 우선 무엇보다도 생각해 볼 것은 속성을 만들고 해당 특성을 사용하여 해당 특성으로 장식 된 클래스의 인스턴스를 자동으로 만드는 것입니다. 내 상황에서 구현할 수있는 클래스의 구현이 실제로 있고 IoC 컨테이너를 사용하고 싶지는 않습니다. 왜냐하면 먼저 요청할 때까지 생성되지 않았고 두 번째는 자동 인스턴스화해야하는 클래스의 특수 집합 일 뿐이 기 때문입니다. 주로 서비스 클래스입니다. 아래 여기에 싱글을NET 어셈블리의 모든 클래스를 자동으로 초기화하는 방법
public abstract class Singleton<T> where T : class
{
private readonly IEventAggregator _eventAggregator =
ServiceLocator.Current.GetInstance<IEventAggregator>();
private static readonly Lazy<T> Instance
= new Lazy<T>(() =>
{
ConstructorInfo[] ctors = typeof(T).GetConstructors(
BindingFlags.Instance
| BindingFlags.NonPublic
| BindingFlags.Public);
if (ctors.Count() != 1)
throw new InvalidOperationException(
String.Format("Type {0} must have exactly one constructor.", typeof(T)));
ConstructorInfo ctor =
ctors.SingleOrDefault(c => !c.GetParameters().Any() && c.IsPrivate);
if (ctor == null)
throw new InvalidOperationException(
String.Format(
"The constructor for {0} must be private and take no parameters.",
typeof(T)));
return (T)ctor.Invoke(null);
});
public static T Current
{
get { return Instance.Value; }
}
}
을 만드는 데 사용하고 코드의 구현은
public class PersonService : Singleton<PersonService>, IPersonService
{
private PersonService()
{
RegisterForEvent<PersonRequest>(OnPersonRequered);
//_serviceClient = ServiceLocator.Current.GetInstance<ICuratioCMSServiceClient>();
}
}
Hwre이 코드가 있어야 모든 유형을 해결하는 데 사용되어 싱글로 정의 된 샘플 클래스입니다 활성화되었습니다.
public class InitOnLoad : Attribute
{
public static void Initialise()
{
// get a list of types which are marked with the InitOnLoad attribute
var types =
from t in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
where t.GetCustomAttributes(typeof(InitOnLoad), false).Any()
select t;
// process each type to force initialize it
foreach (var type in types)
{
// try to find a static field which is of the same type as the declaring class
var field =
type.GetFields(System.Reflection.BindingFlags.Static
| System.Reflection.BindingFlags.Public
| System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance).FirstOrDefault(f => f.FieldType == type);
// evaluate the static field if found
//if (field != null) field.GetValue(null);
}
}
}
나는 Stackoverflow에서 코드 조각을 발견했으며 정말 재미 있지만 init 클래스를 관리하지 못했다고 생각합니다.
요청할 때 인스턴스화되는 클래스의 문제점은 무엇입니까? 싱글 톤의 광범위한 사용은 장기적으로 당신을 물들 일 것입니다. – lboshuizen
이들은 모듈 당 서비스 클래스이므로,이 클래스는 최소한의 수의 클래스 만 사용합니다. 여기서의 문제는 firtordefualt 메소드의 닫는 메소드가 아무 것도 반환하지 않는 곳입니다 –
'RuntimeHelpers.RunClassConstructor' – SLaks