C
C#9mo ago
Yawnder

DI: Registration of services through a builder.

I'm making a library to be "registered" like services.AddMyFeature(builder => ...); The builder can be used a bit like ASP's registration with the AddAuthorization, AddPolicy, etc. For example:
services.AddAuthorization(c =>
{
var tenantAuthRequirement = new TenantAuthorizationRequirement();
c.AddPolicy(Policies.TenantAuthenticatedUser, p =>
{
p.AddAuthenticationSchemes(PreSharedKeyAuthenticator.Scheme, PartitionConstants.AuthenticationSchemaBearer)
.RequireAuthenticatedUser()
.AddRequirements(tenantAuthRequirement);
});
}
services.AddAuthorization(c =>
{
var tenantAuthRequirement = new TenantAuthorizationRequirement();
c.AddPolicy(Policies.TenantAuthenticatedUser, p =>
{
p.AddAuthenticationSchemes(PreSharedKeyAuthenticator.Scheme, PartitionConstants.AuthenticationSchemaBearer)
.RequireAuthenticatedUser()
.AddRequirements(tenantAuthRequirement);
});
}
I want one of these builder.AddSubFeature() (the equivalent of the c.AddPolicy(...) above) to add some more registrations in services. The way I was thinking about it was to have an internal List<Action<IServiceCollection>> on the builder in which builder.AddSubFeature() would add custom registrations. Any better suggestion?
7 Replies
Yawnder
YawnderOP9mo ago
But that has absolutely nothing to do with my question.
WAASUL
WAASUL9mo ago
My bad, perhaps I misunderstood.
Yawnder
YawnderOP9mo ago
It means my question wasn't clear then!
WAASUL
WAASUL9mo ago
Based on this builder.AddSubFeature() maybe an extension would help.
Yawnder
YawnderOP9mo ago
As of now, it is an extension method that adds the registration in builder.CustomRegistrations, which is internal. I'm wondering if there is a better known pattern to do that.
WAASUL
WAASUL9mo ago
Are you looking for a way to register you services separately?
Yawnder
YawnderOP9mo ago
A way for that extension method to register services, while this extension methods only has access to a builder, not the IServiceCollection. I'm not looking for a method that just works; mine does. I'm looking for a known pattern that I should follow rather than my makeshift method.
Want results from more Discord servers?
Add your server