gpt4 book ai didi

c# - 如何在 C# 中使用 Autofac 而不是单例?

转载 作者:行者123 更新时间:2023-12-05 03:13:44 28 4
gpt4 key购买 nike

我使用了单例模式 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>

因为我在 MyClass 中有 Language:

public static Localizer Language { get { return _Lazy.Value; } }

但是现在我没有这个属性。

How can I call Translate method in Index.cshtml as I do not have static property like previous.

最佳答案

您只需要将 MyClass 注册为 SingleInstance 到您的容器:

var builder = new ContainerBuilder();
builder.RegisterType<MyClass>().As<IMyClass>().SingleInstance();

然后在你需要的地方注入(inject):

public AnotherClass(IMyClass myClass)
{
_myClass = myClass;
}

虽然它可能是您想要的单个实例的缓存。在那种情况下:

builder.RegisterType<MemoryCacheManager>().SingleInstance();

然后:

public MyClass(MemoryCacheManager cache)
{
_cacheManager = cache;
LoadCacheData();
}

编辑:

您需要做的第一件事是在您的 Application_Start 类中设置 DependencyResolver(为此您需要获取 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 注入(inject)到 Controller 的构造函数中:

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>

关于c# - 如何在 C# 中使用 Autofac 而不是单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29025491/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com