I realize this question is asked a lot. But I cannot figure out the solution to this problem.
The thing i am trying to resolve is create three seperate inter
The solution provided does not resolve solution scanning. But answers the question.
Now you see there is a solution working with very similar code as the above.
But there is a constraint to it. Your interface needs to be in the same project as your builder and base implementation.
You may as well view this as a step-by-step guide on how to achieve this.
Our Solution Looks sth like this.
Three solution projects
Sth.Core --> Class Library.
Sth.Services --> Class Library.
Sth.Web --> ASP.NET Core MVC project.
The Sth.Core has our three lifetime interface which our Services need to inherit from.
Sth.Core
All three are empty interfaces.
Sth.Web We need to edit 2 files here. The Program.cs, Startup.cs
Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory()) //Add this
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
}
Startup.cs
Add this method to your startup class.
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new SthModule()); // This is the autofac Module. We add it later at the Services Project
}
Now for our Services Project.
Here we need to create our autofac module. That we said inside asp.net app to instantiate.
public class SthModule : Module
{
protected override void Load(ContainerBuilder builder)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
builder
.RegisterAssemblyTypes(assemblies)
.Where(t => t.GetInterfaces().Any(i => i.IsAssignableFrom(typeof(ISthScopedService))))
.AsImplementedInterfaces()
.InstancePerLifetimeScope(); // Add similar for the other two lifetimes
base.Load(builder);
}
}
The above code will sacn all the Services project and add all the classes that inherit from the ISthScopedService and register them to the container.
Here are our ServiceInstances inside the Service Project.
EpisodeService.cs
public class EpisodeServices : IEpisodeService
{
public IList GetEpisodes()
{
return new List
{
new Episode { Id = 1, Name = "Imposter Syndrome", Description = "Imposter syndrome" }
};
}
}
And the interface.
public interface IEpisodeService : ISthCommonService
{
IList GetEpisodes();
}
Now we have implemented assembly scanning(auto registration) for our services project.