依赖注入,注入参数 [英] Dependency injection, inject with parameters

查看:209
本文介绍了依赖注入,注入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DI的vNext实现. 如何将参数传递给构造函数? 例如,我上课:

I'm using vNext implementation of DI. How to pass parameters to constructor? For example, i have class:

public class RedisCacheProvider : ICacheProvider
{
    private readonly string _connectionString;

    public RedisCacheProvider(string connectionString)
    {
        _connectionString = connectionString;
    }
    //interface methods implementation...
}

服务注册:

services.AddSingleton<ICacheProvider, RedisCacheProvider>();

如何将参数传递给RedisCacheProvider类的构造函数? 例如Autofac:

How to pass parameter to constructor of RedisCacheProvider class? For example for Autofac:

builder.RegisterType<RedisCacheProvider>()
       .As<ICacheProvider>()
       .WithParameter("connectionString", "myPrettyLocalhost:6379");

推荐答案

您可以提供一个委托来手动实例化您的缓存提供程序,也可以直接提供一个实例:

You can either provide a delegate to manually instantiate your cache provider or directly provide an instance:

services.AddSingleton<ICacheProvider>(provider => new RedisCacheProvider("myPrettyLocalhost:6379"));

services.AddSingleton<ICacheProvider>(new RedisCacheProvider("myPrettyLocalhost:6379"));

请注意,即使容器实现IDisposable,该容器也不会显式处理手动实例化的类型.请参阅有关服务的处理以获取更多信息.

Please note that the container will not explicitly dispose of manually instantiated types, even if they implement IDisposable. See the ASP.NET Core doc about Disposal of Services for more info.

这篇关于依赖注入,注入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆