带构造函数参数的 RegisterSingleton

RegisterSingleton with constructor parameter

我在单独的 DLL 项目中有一个名为 CustomerService 的服务,该服务需要主项目中 App.config 的连接字符串。这是 CustomerService:

public class CustomerService : ICustomerService
{
    private string _mySQLConnectionString;

    public CustomerService(string mySQLConnectionString)
    {
        _mySQLConnectionString = mySQLConnectionString;
    }

    public List<Customer> GetCustomerList()
    {
        return new List<Customer>();
    }
}

我想用 containerRegistry.RegisterSingleton 注册此服务,如下所示。如何添加构造函数参数?是否有任何其他解决方案可以在单独的 DLL 项目中与多个服务共享来自 App.config 的连接字符串。

public void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterSingleton<ICustomerService, CustomerService>();
}

注意:多个服务连接 MySQL 服务器所需的连接字符串。

问题第二部分:如何注册另一个称为“服务”的单例(示例:SocketService)并与其他已注册的单例共享该单例,例如我的 CustomerServiceItemService?所以所有注册的“服务”都可以从 SocketService.

调用 Connect() 方法

您可以先创建类型的实例,然后调用RegisterInstance

var mySQLConnectionString = "...";
var customerService = new CustomerService(mySQLConnectionString);
containerRegistry.RegisterInstance(customerService);

另一种方法是使用工厂方法,在 RegisterSingleton.

的重载上提供
var mySQLConnectionString = "...";
containerRegistry.RegisterSingleton<CustomerService>(() => new CustomerService(mySQLConnectionString));

如果您需要更大的灵活性,例如解析其他类型,对容器使用另一个重载。

containerRegistry.RegisterSingleton<AnyService>(containerProvider =>
{
   var anyOtherService = containerProvider.Resolve<AnyOtherService>();
   // ...other complex setups
   return new AnyService(anyOtherService);
});

How can I register another singleton call it "service" (example: SocketService) and share that singleton for other registered singletons for example my CustomerService or ItemService? So all registered "service" can call the my Connect() method from the SocketService.

在您的 CustomerService 中将依赖项指定为构造函数参数(最好使用接口来简化单元测试)并将其及其依赖项注册到容器中。

public class CustomerService : ICustomerService
{
    private string _mySQLConnectionString;

    public CustomerService(string mySQLConnectionString, ISocketService socketService)
    {
        _mySQLConnectionString = mySQLConnectionString;
        // ...other code.
    }
    
    // ...other code.
}
var mySQLConnectionString = "...";

containerRegistry.RegisterSingleton<ISocketService, SocketService>();
containerRegistry.RegisterSingleton<CustomerService>(containerProvider =>
{
   var sockertService = containerProvider.Resolve<SocketService>();
   // ...other complex setups
   return new CustomerService(mySQLConnectionString, sockertService);
});

一旦您解决了这些类型中的任何一个,容器将负责设置依赖项。