Using Scrutor for Register interface assembly

1.1k Views Asked by At

I'm using Scrutor 8.1 to register all types in my assembly that implement interfaces (ASP.NET Core 6).

I have a code structure similar to the following (all type members omitted for brevity):

services.AddSingleton(typeof(IRepository<>), typeof(Repository<>));

I use this code in program.cs:

builder.Services.Scan(scan => scan
        .FromAssemblies(Assembly.GetExecutingAssembly())
        .FromAssemblyOf<IUnitOfEntity>()
        .AddClasses()
        .UsingRegistrationStrategy(RegistrationStrategy.Skip)
        .AsMatchingInterface()
        .WithTransientLifetime());

But I get this error :

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType:

Microsoft.AspNetCore.Authorization.IAuthorizationService Lifetime: Transient ImplementationType:

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService': Unable to resolve service for type 'TIR.NetCore.IUnitOfEntity' while attempting to activate 'TIR.NetCore.BaseLoginService'.) (Error while validating the service descriptor 'ServiceType:

Microsoft.AspNetCore.Authorization.IAuthorizationHandlerProvider Lifetime: Transient ImplementationType:

Microsoft.AspNetCore.Authorization.DefaultAuthorizationHandlerProvider':

Unable to resolve service for type 'TIR.NetCore.IUnitOfEntity' while attempting to activate 'TIR.NetCore.BaseLoginService'.) (Error while validating the service descriptor 'ServiceType:
Microsoft.AspNetCore.Authorization.Policy.IPolicyEvaluator Lifetime: Transient ImplementationType:
Microsoft.AspNetCore.Authorization.Policy.PolicyEvaluator': Unable to resolve service for type 'TIR.NetCore.IUnitOfEntity' while attempting to activate 'TIR.NetCore.BaseLoginService'.)

1

There are 1 best solutions below

1
Xinran Shen On BEST ANSWER

FromAssemblyOf<>, FromAssembliesOf - Scan the assemblies containing the provided Type or Types.

AddClasses() - Add all public, non-abstract classes.

AddClasses(publicOnly) - Add all non-abstract classes. Set publicOnly=false to add internal/private nested classes too.

AddClass(predicate) - Run an arbitrary action to filter which classes include. This is very useful and used extensively, as shown below.

AddClasses(predicate, publicOnly) - A combination of the previous two methods.

So, You can change your code like:

builder.Services.Scan(scan => scan
    .FromAssemblyOf<ITest>()
    .AddClasses(classes => classes.AssignableTo<ITest>())
    .UsingRegistrationStrategy(RegistrationStrategy.Skip)
    .AsImplementedInterfaces()
    .WithTransientLifetime());