.net core 依赖注入的基本用发

本文详细介绍了在C#中如何通过依赖注入将接口与其实现类进行解耦,展示了具体的代码示例,包括定义接口、实现接口的类、依赖注入配置以及在控制器中使用依赖的服务。
namespace KeeSoft.Common 
{ 
    //定义一个User接口
    public interface IUser
    {
        string GetUserId();
    }

    //实现IUser接口 创建一个User
    public class User : IUser 
    {
       public string GetUserId() 
       { 
            return "User"; 
       } 
    }

    //实现IUser接口 创建一个User
    public class UserManager : IUser
    {
        public string GetUserId()
        {
             return "UserManager";
        }
    }
}

如何将依赖注入到类中使用

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<KeeSoft.Common.IUser, KeeSoft.Common.UserManager>();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }

如何使用注入的依赖

namespace Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
       KeeSoft.Common.IUser User { get; }

       public ValuesController(KeeSoft.Common.IUser _user)
        {
            User = _user;
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return User.GetUserId();
        }
    }
}

转载于:https://my.oschina.net/kee1986/blog/2876454

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值