我的应用程序的服务层中有多个类。假设我需要从控制器中的 AbcService.cs 访问某些方法。然后,我需要从同一个控制器中的 XyzService.cs 访问一些方法。然后另一个.......为此,我需要在构造函数中分别创建每个服务类的对象。此外,如果我需要在另一个控制程序中访问这些方法,我将再次创建 AbcService、XyzService 等对象。我希望有一个实例可以让我访问所有服务类的方法。就像是:
generalService.AbcService.MethodName();
generalService.AbcService.MethodName();
我如何以最好的方式做到这一点?
不幸的是,在 C# 中,您不能同时从两个类继承,例如
public class CombinedService : AbcService, XyzService {
}
不可能。
但是,您可以使用静态方法使每个服务只有一个实例,如下所示:
public static class ServiceManager {
// The variable holding the instance
private static AbcService _abcService = null;
// Access to the instance and single instance creator
public static AbcService AbcServiceInstance {
get {
if (_abcService == null) {
// Create your Instance here
_abcService = new AbcService();
}
return _abcService;
}
}
// The variable holding the instance
private static XyzService _xyzService = null;
// Access to the instance and single instance creator
public static XyzService XyzServiceInstance {
get {
if (_xyzService == null) {
// Create your Instance here
_xyzService = new XyzService();
}
return _xyzService;
}
}
}
因为它们是静态的,所以你可以从代码中的任何地方访问它们,只需像这样调用静态类属性:
ServiceManager.AbcServiceInstance.SomeMethod();
ServiceManager.XyzServiceInstance.SomeMethod();
您还可以像这样缩短实例化和访问器:
private static AbcService _abcService = new AbcService();
public static XyzService XyzServiceInstance {
get { return _abcService; }
}
如果可以像这样创建实例并且不需要更多参数或配置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句