.NET Core简单注入

版权声明:版权所有,需要请联系作者 https://blog.csdn.net/weixin_42930928/article/details/87704629

最近在看公众号【草根专栏】发布的.net core 2.2的中级视频教程。在blog 中整理了系列教程:

.net core 2.2中级教程

今天写一下关于自定义服务的注入功能

实现一个服务接口:

public interface IWelcomService
{    
    string GetMessage();
}

具体实现类:

public class WelcomeService:IWelcomService
{    public string GetMessage()    
    {        
        return "Hello from IWelcome Service";
    }
}

在Startup类中的ConfigureServices方法中添加如下代码

//添加单例模式的服务注册            
services.AddSingleton<IWelcomService, WelcomeService>();
 
//services.AddTransient<IWelcomService,WelcomeService>();            
//每次http请求,生成一个            
//services.AddScoped<IWelcomService, WelcomeService>();

在HomeController的控制器的构造函数中进行注入

public class HomeController    
{        
    private IWelcomService _welcomeService;
    public HomeController(IWelcomService welcomService)       
    {            
        _welcomeService = welcomService;
     }        
     public string Index()        
     {            
         return _welcomeService.GetMessage();        
     }    
}

这样我们就实现了一个简单的注入功能


猜你喜欢

转载自blog.csdn.net/weixin_42930928/article/details/87704629