2019独角兽企业重金招聘Python工程师标准>>>
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();
}
}
}