Search code examples
c#autofacioc-containerasp.net-core-7.0autofac-module

Autofac assembly scanning with interfaces


Project is built with .NET 7 MVC.

I have created 3 interfaces in my "Application" class library. I will implement these interfaces on my other interfaces or classes.

I want the dependencies to be automatically resolve by scanning the assembly, like if the interface or class is implementing "ITransientLifetime" then it should resolve as "InstancePerDependency". If any class or interface has "ISingletonLifetime" then it should resolve as Singleton Lifetime.

Below is my project architecture.
Project Architecture

Here is my code from Application class library.
ISingletonLifetime.cs

public interface ISingletonLifetime 
{
}

ITransientLifetime.cs

public interface ITransientLifetime
{
}

IEmailSender.cs

public interface IEmailSender : ISingletonLifetime
{
   void SendEmail(string email);
}

EmailSender.cs

public class EmailSender : IEmailSender
{
    public void SendEmail(string email)
    {
       throw new NotImplementedException();
    }
} 

And here is the code from "Mvcapp"
AutofacIocContainer.cs

public class AutofacIocContainer : Module
{
    private readonly Type singletonInterface = typeof(ISingletonLifetime);
    private readonly Type transientInterface = typeof(ITransientLifetime);
    protected override void Load(ContainerBuilder builder)
    {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        builder
         .RegisterAssemblyTypes(assemblies)
         .Where(t => t.GetInterfaces().Any(i => i.IsAssignableFrom(transientInterface)))
         .AsImplementedInterfaces()
         .InstancePerDependency();

          base.Load(builder);
     }   
 }

Program.cs

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder =>
{
      containerBuilder.RegisterModule(new AutofacIocContainer());
})

Can anybody guide me on this. This link is the same what I am looking for but I am unable to resolve my dependency IEmailSender. I am getting below error:

InvalidOperationException: Unable to resolve service for type 'Application.Interfaces.IEmailSender' while attempting to activate 'MvcAppCore.Controllers.HomeController'.

Also I am thinking on how to handle the scenario like below:

public class Test : ISingletonLifetime, ITransientLifetime
{
}

Thank You


Solution

    • You marked your IEmailSender as ISingletonLifetime
    • You are registering only implementations of ITransientLifetime
    • Hence you cannot resolve IEmailSender because it is not registered.

    A valid way to handle

    public class Test : ISingletonLifetime, ITransientLifetime
    {
    }
    

    Is by throwing an exception at composition time. But then, I do not know your requirements in handling this.