[英]Global access to an object from anywhere
是否有某種技巧、設計模式或其他一些通用方法可以使對象“全局”可用,以便您可以根據需要從應用程序訪問對象,以便可以在應用程序的加載過程中加載它(無論是控制台等桌面應用程序,還是 MVC 等 Web 應用程序)
我基本上是在尋找可以在主啟動方法中初始化的東西,並且無需將它傳遞給每個方法來使用它就可以使用它,同時它會保留它的狀態和初始化它的屬性。
正如我在評論中提到的,這看起來像一個XY 問題。 我相信正確的解決方案是使用 IoC/DI,而不是實際執行全局變量,大多數堆棧溢出的人都認為這是禁忌。 我更喜歡使用Autofac (沒有隸屬關系,並且有很多 DI 框架可供選擇)。 這允許每個對象簡單地請求(通過構造函數注入或不推薦的屬性注入方法)它需要使用的對象才能正常運行。 這減少了耦合並有助於測試代碼(單元測試)。
using System;
using Autofac;
public class Program
{
public static void Main()
{
// Start configuring DI
IoCConfig.Start();
// Start "scope" in which Autofac builds objects "in"
using(var scope = IoCConfig.Container.BeginLifetimeScope())
{
// Resolve the Worker
// Autofac takes care of the constructing of the object
// and it's required parameters
var worker = scope.Resolve<Worker>();
worker.DoWork();
}
}
}
// the class that does work, it needs the Configuration information
// so it is added to the constructor parameters
public class Worker
{
private readonly string _connectionString;
public Worker(IConfiguration config)
{
_connectionString = config.ConnectionString;
}
public void DoWork()
{
// Connect to DB and do stuff
Console.WriteLine(_connectionString);
}
}
public static class IoCConfig
{
public static IContainer Container { get; private set; }
public static void Start()
{
var builder = new ContainerBuilder();
// Register Global Configuration
builder.Register(c => new Configuration{
ConnectionString = "my connection string" // or ConfigurationManager.ConnnectionString["MyDb"].ConnectionString;
})
.As<IConfiguration>();
// Register an concrete type for autofac to instantiate
builder.RegisterType<Worker>();
Container = builder.Build();
}
private class Configuration : IConfiguration
{
public string ConnectionString { get; set; }
}
}
public interface IConfiguration
{
string ConnectionString { get; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.