A few months ago I built a very simply still effective plugin system with autofac modules in ASP.Net Core 1.1 like this
In startup.cs
public IServiceProvider ConfigureServices(IServiceCollection services)
{
var builder = new ContainerBuilder();
builder.RegisterModule<AutofacModule>();
builder.Populate(services);
var ApplicationContainer = builder.Build();
return new AutofacServiceProvider(ApplicationContainer);
}
then in AutofacModule.cs
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<AuthMessageSender>().As<IEmailSender>();
builder.RegisterType<AuthMessageSender>().As<ISmsSender>();
builder.RegisterType<HttpClient>().As<HttpClient>();
foreach (var assembly in LoadAllAssemblies())
{
builder.RegisterAssemblyModules(assembly);
}
}
private IEnumerable<Assembly> LoadAllAssemblies()
{
string assemblyPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "");
var allAssemblies = new List<Assembly>();
foreach (string dll in Directory.GetFiles(assemblyPath, "*.dll"))
{
try
{
var assembly = Assembly.LoadFile(dll);
if (!assembly.GetTypes().Any(type => type.IsSubclassOf(typeof(Autofac.Module))))
{
continue;
}
allAssemblies.Add(assembly);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
continue;
}
}
return allAssemblies;
}
then I could load modules from assemblies like this:
public class AutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<UserService>().As<IUserService>();
builder.RegisterType<DashboardService>().As<IDashboardService>();
builder.RegisterType<DetailPageService>().As<IDetailPanelService>();
builder.RegisterType<PlanningService>().As<IPlanningService>();
builder.RegisterType<PlanningRepository>().As<IPlanningRepository>();
}
}
I had to copy assemblies to the running web app bin directory to work, or reference all assemblies in the main web project. All the assemblies were .Net Framework Class Libraries. After a while I updated the whole solution to Asp.Net Core 2.0, and Autofac module containing assemblies changed to .Net Core Class Libraries. Now, autofac modules are still found, and registered via RegisterAssemblyModules, but load method does not called anymore. I realized, if I create another .Net Framework Library project with autofac module, and reference it, it is still loading as expected, and load method called. So it seems to me this problem is related to .Net Core Libraries.
Anybody can explain me this, knows any solution, workaround, or can recommend another architecture for plugin system with autofac?