Resolve and Register services using Scrutor in Asp.net core

585 Views Asked by At

i have an interface(IDomainService) and a (lot) like it in my app which i mark more interfaces with it(IProductionLineTitleDuplicationChecker ) like what u will see in the rest:

public interface IDomainService
    {

    }
public interface IProductionLineTitleDuplicationChecker : IDomainService
    {
        ///
    }

and the implementation like this:

public class ProductionLineTitleDuplicationChecker : IProductionLineTitleDuplicationChecker
    {
        private readonly IProductionLineRepository _productionLineRepository;

        public ProductionLineTitleDuplicationChecker(IProductionLineRepository productionLineRepository)
        {
            _productionLineRepository = productionLineRepository;
        }

        public bool IsDuplicated(string productionLineTitle)
        {
            ///
        }
    }

right now im using the built-in DI-container to resolve and register the services but i want to change it and use scrutor instead

how can i resolve and register my Services using scrutor?

4

There are 4 best solutions below

3
digital_jedi On

You could just leverage the Scrutor extension methods for Microsoft.Extensions.DependencyInjection.IServiceCollection. In your Startup.cs:

public void ConfigureServices(IServiceCollection serviceCollection)
{
    serviceCollection
        .Scan(x => x.FromAssemblyOf<ProductionLineTitleDuplicationChecker>()
            .AddClasses()
            .AsImplementedInterfaces()
            .WithTransientLifetime());
}
0
Chen On

I think your situation is consistent with this post, please try to use the way inside:

services.Scan(scan => scan
    .FromAssemblyOf<IProductionLineTitleDuplicationChecker>()
    .AddClasses(classes => classes
        .AssignableTo<IProductionLineTitleDuplicationChecker>())
.AsImplementedInterfaces()
.WithScopedLifetime());
1
Sock On

I think this should work

public void ConfigureServices(IServiceCollection serviceCollection)
{
    services.Scan(scan => scan
        .FromAssemblyOf<IProductionLineTitleDuplicationChecker>()
        .AddClasses(classes => classes.AssignableTo<IDomainService>())
            .AsImplementedInterfaces()
            .WithScopedLifetime());
}
0
HassanJalali On

Here is the solution:

 protected IServiceCollection _serviceCollection;
 public virtual void Register(IServiceCollection serviceCollection, )
        {
            _serviceCollection = serviceCollection;
             RegisterTransient<IDomainService>();
        }

        private void RegisterTransient<TRegisterBase>()
        {
            _serviceCollection.Scan(s =>
                s.FromApplicationDependencies()
                    .AddClasses(c => c.AssignableTo<TRegisterBase>())
                    .UsingRegistrationStrategy(RegistrationStrategy.Throw)
                    .AsMatchingInterface()
                    .WithTransientLifetime());
        }