猿问

在密封类中实例化另一个类

在密封类中实例化另一个类的推荐方法是什么:


public sealed class AvayaService

{

    private static Lazy<AvayaService> lazy =

       new Lazy<AvayaService>(() => new AvayaService());


    public static AvayaService AvayaServiceInstance

    {

        get

        {

            if (!lazy.IsValueCreated)

                lazy = new Lazy<AvayaService>(() => new AvayaService());

            return lazy.Value;

        }

    }


    private AvayaService()

    {

    }


    public static Response GetResponse(Request request)

    {

       var _repository = new Repository(); //  what is the best way to get the instance here


    }

}


public class Repository : IRepository

{

   ...

}

我正在尝试学习密封类和惰性实例化,但是我正在思考在密封类中实例化另一个类的推荐方法是什么?


明月笑刀无情
浏览 255回答 1
1回答

慕无忌1623718

这方面没有“建议”。如果您已阅读建议,请再次阅读,这很可能只是一个练习。它给了你一个想法,但在实际项目中使用这个想法取决于你。有时,这些练习展示了相反的方法。有时,存储库所有者会规定违反您之前阅读过的任何规则的样式,这完全没问题。这是我认为有助于尝试的另一个实例化练习:永远不要实例化除值对象之外的任何内容。将实例化委托给容器。避免单例模式,但将您的服务注册为容器中的单例。通过这种方式,您的代码将如下所示:public sealed class AvayaService{&nbsp; &nbsp; private readonly IRepository _repository;&nbsp; &nbsp; public AvayaService(IRepository repository)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if(repository == null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new ArgumentNullException();&nbsp; &nbsp; &nbsp; &nbsp; _repository = repository;&nbsp; &nbsp; }&nbsp; &nbsp; public static Response GetResponse(Request request)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // use _repository&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答