0

好的首先让我说,我正在考虑的是创建属性并使用该属性来自动创建用该属性装饰的类的实例。确实有可以在我的情况下构建的类的实现,我不想在这里使用 IoC 容器,因为首先我认为它们在请求之前不会创建,其次这仅适用于需要自动实例化的特殊类集这些主要是服务类。下面是用于创建单例的代码的实现

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 上发现了该代码片段,我认为它真的很有趣,但没有设法初始化类。

4

1 回答 1

1

在对特定类进行任何引用之前,您可以使用静态构造函数运行该类的代码。这是来自 MS 的一些信息:http: //msdn.microsoft.com/en-us/library/k9x6w0hc (v=vs.100).aspx 。

编辑:Jon Skeet 有一篇关于这个主题的文章可能会回答你的问题。它也有代码示例。

于 2012-10-15T23:46:59.457 回答