Appearance
Web应用
在Web中,希望Controller或PageModel中自动注入,需要引用AsDI.Core.Web, 可以通过NuGet进行安装
sh
dotnet add package AsDI.Core --version 2.0.0
dotnet add package AsDI.Core.Web --version 2.0.0此时创建一个Web MVC运用程序或Web API运用程序,在Program的Main函数中,需要开启AsDI的支持,如下所示:
C#
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
...
//将原来的Builder.Build()改成 builder.AsBuild()
//var app = builder.Build();
var app = builder.AsBuild();
...
app.Run();
}
}有了以上代码,即可在Web中,自由的使用AsDI的所有特性及功能。例如在Controller中,自动注入:
C#
namespace WebApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class HelloController : ControllerBase
{
private readonly IHelloService helloService;
public HelloController(IHelloService helloService)
{
this.helloService = helloService; //自动注入HelloService
}
[HttpGet]
public string Get()
{
return helloService.Say("World");
}
}
}需要注意的是,现在Controller是一个类型,不是一个接口,无法进行切面和动态代理。后续AsDI会推出自己的RestAPI的调用方式