【发布时间】:2014-06-04 00:15:38
【问题描述】:
我在大多数控制器(使用 Unity.Mvc5)中使用了至少两个服务(例如,IVendorService 和 IFooService)。 我想为这些控制器创建一个通用助手。我正在考虑使用延迟加载和 Unity 创建一个单例类。 我在其中一篇博客中读到,统一要求构造函数是公开的。
这可行,但这并不是真正使用单例模式。
AppHelper.cs
public sealed class AppHelper
{
private static IList<Vendor> _vendorList;
private static IList<Foo> _fooList;
public AppHelper(IFooService fooService, IVendorService vendorService)
{
if (fooService != null) _vendorList = vendorService.GetVendors();
if (vendorService != null) _fooList = fooService.GetFoo();
}
public static IList<Vendor> VendorList
{
get { return _vendorList; }
}
public static IList<Foo> FooList
{
get { return _fooList; }
}
}
我已经尝试过这种方式,但它给了我一个编译错误。
AppHelper.cs
public sealed class AppHelper
{
private static readonly Lazy<AppHelper> instance = new Lazy<AppHelper>(() => new AppHelper(fooService, vendorService));
private static IList<Vendor> _vendorList;
private static IList<Foo> _fooList;
private AppHelper(IFooService fooService, IVendorService vendorService)
{
_vendorList = vendorService.GetVendors();
_fooList = fooService.GetFoo();
}
public static AppHelper Instance()
{
return instance.Value;
}
public static IList<Vendor> VendorList
{
get { return _vendorList; }
}
public static IList<Foo> FooList
{
get { return _fooList; }
}
}
有什么建议吗?
【问题讨论】:
-
为什么使用单例反模式本身很重要?对你来说,你的目标是从你拥有的有效代码中获得什么?
-
好点。我的主要原因是使用有效的代码,我需要在每个控制器文件中实例化 AppHelper。所以我想看看是否有一种方法可以在 Global.asax.cs 文件中执行 AppHelper.Instance()。
-
哦,您只使用控制器中的这些属性?
-
我也在我的观点中使用它。
标签: c# asp.net-mvc singleton unity-container