我使用了单例模式a使用静态属性,构造函数
public class MyClass
{
private readonly MemoryCacheManager _cacheManager;
private static readonly Lazy<MyClass> _Lazy = new Lazy<MyClass>(() => new MyClass());
public static MyClass Language { get { return _Lazy.Value; } }
private MyClass()
{
_cacheManager = new MemoryCacheManager();
LoadCacheData();
}
// Rest of class
}
我试过在global.asax
中使用Autofac:
protected void Application_Start()
{
var builder = new ContainerBuilder();
builder.RegisterType<MemoryCacheManager>().SingleInstance();
}
在MyClass
构造函数中:
private MyClass(MemoryCacheManager cache)
{
_cacheManager = cache;
LoadCacheData();
}
public string Translate(string language)
{
var translation = _cacheManager.GetValueFromCache();
}
我想在Index.cshtml
以前我直接这样做过:
<h4>@MyClass.Language.Translate("Welcome", Model.Language)</h4>
正如Language
中的MyClass
所示:
public static Localizer Language { get { return _Lazy.Value; } }
但现在我没有这个属性。
如何在Index.cshtml中调用Translate方法,因为我没有像以前那样的静态属性。
答案 0 :(得分:1)
您只需要将MyClass
注册为SingleInstance
与您的容器:
var builder = new ContainerBuilder();
builder.RegisterType<MyClass>().As<IMyClass>().SingleInstance();
然后注入你需要的地方:
public AnotherClass(IMyClass myClass)
{
_myClass = myClass;
}
虽然它可能是您希望单个实例的缓存。在那种情况下:
builder.RegisterType<MemoryCacheManager>().SingleInstance();
然后:
public MyClass(MemoryCacheManager cache)
{
_cacheManager = cache;
LoadCacheData();
}
修改强>
您需要做的第一件事是在DependencyResolver
课程中设置Application_Start
(您需要为此获取Autofac MVC Integration NuGet包):
protected void Application_Start()
{
this.RegisterAutoFac();
// Rest of method
}
private void RegisterAutoFac()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<MyClass>().As<IMyClass>();
builder.RegisterType<MyCache>().As<IMyCache>().SingleInstance();
var container = builder.Build();
// Setup the dependency resolver
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
然后你需要将MyClass
注入你的控制器的构造函数中:
public class TestController : Controller
{
private readonly IMyClass _myClass;
public TestController(IMyClass myClass)
{
_myClass = myClass;
}
// Rest of the controller
}
然后,当您为自己创建模型时,可以从MyClass
获取所需数据:
public ActionResult Index()
{
var model = new ExampleModel
{
WelcomeMessage = _myClass.Translate("Welcome")
};
return View(model);
}
在你看来:
<h4>@Model.WelcomeMessage</h4>