Extensions of native .NET dependency injection with Autowired, provides a way to support properties and fields injection.
All lifetimes and generics are now supported. And using ILGeneratorEx to speed up the setter.
public class Service{
[Autowired]
private readonly IService dependency;
[Autowired]
private IService Dependency { get; set; }
}
IServiceProvider provider = new ServiceCollection()
.Add(...)
.BuildAutowiredServiceProvider(static x=>x.BuildServiceProvider());
IService service = provider.GetService<IService>();
In ASP.NET CORE MVC :
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers() //register controllers
.AddControllersAsServices() // add controllers as services
.UseAutowiredControllers(); // use auto wired controllers
builder.Host.UseAutowiredServiceProviderFactory(); // autowired services
Tests could be found in ServiceTest.cs , which shows higher performance than Autofac and is close to native.
Meanwhile, you can still use your attribute, only need to provide it at build time :
IServiceProvider provider = collection.BuildAutowiredServiceProvider<YourAutowiredAttribute>(...);
builder.Services.AddControllers()
.AddControllersAsServices()
.UseAutowiredControllers<YourAutowiredAttribute>();
builder.Host.UseAutowiredServiceProviderFactory<YourAutowiredAttribute>();