Rebuild from Microsoft.Extensions.DependencyInjection
Export service resolve callback
class ServiceProviderEx : IServiceProvider;
ServiceProviderEx provider = new ServiceCollection()
.Add...(...)
...
.BuildServiceProviderEx(options...);
-
ListenKind
indicates which kind of behavior to be listenenum ServiceResolvedKind{ None = 0, // nothing Factory = 1, // service resolved from Func<...> Constructor = 2, // service resolved by ctor Constant = 4, // service resolved from registered instance IEnumerable = 8, // service required by IEnumerable<> ServiceProvider = 16, // require IServiceProvider }
-
public enum CallbackTime { Finally, // ServiceResolved will be triggered before GetService() returned Immediately, // ServiceResolved will be triggered after each instance resolved }
-
Finally
Moderesolve A => resolve B => resolve C => trigger A => trigger B => trigger C
finally mode can resolve circular dependency
-
Immediately
Moderesolve A => trigger A => resolve B => trigger B => resolve C => trigger C
immediately mode can let dependency full-filled before injected
-
ServiceProviderEx.ServiceResolved
event to be triggered when service resolved
delegate void ServiceResolvedHandler(
IServiceProvider provider, // service provider which resolved this service
Type serviceType, // required service type
object instance, // resolved instance
ServiceResolveKind kind // resolved kind
);
provider.ServiceResolved += (provider, serviceType, instance, kind) => {
// do something
};
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class AutowiredAttribute(Type? serviceType = null) : Attribute
{
public object? Key { get; set; } // key for keyed service
public bool GetServices { get; set; } // IEnumerable<...>
}
Usage
class Service{
[Autowired]
private IService? service;
[Autowired(typeof(IService))]
public Service service { get; init; }
[Autowired(typeof(IService), Key="string key", GetServices=true)]
public IEnumerable<Service> keyedService { get; init; }
}
Auto inject service from props/fields which marked with AutowiredAttribute
IServiceCollection collection; // from somewhere
IServiceProvider provider = collection.BuildAutowiredServiceProviderEx();
Autowired service provider for ASP.NET
var builder = WebApplication.CreateBuilder(args);
... multiple configures ...
builder.Host.UseAutowiredServiceProviderFactory(); // should be configured before Build()
var app = builder.Build();
if you want to use AutowiredAttribute
in Controller
remember to
builder.Services.AddControllers()
.AddControllersAsServices(); // register controllers as services