Skip to content

Commit

Permalink
autofac integration
Browse files Browse the repository at this point in the history
  • Loading branch information
a-patel committed Apr 22, 2021
1 parent ca0fdfb commit bce047f
Show file tree
Hide file tree
Showing 10 changed files with 193 additions and 73 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
# Autofac in .NET

Example projects that consume and demonstrate Autofac functionality and integration in ASP.NET.
> Demo: Example project that consume and demonstrate Autofac functionality and integration in ASP.NET/.NET Core.


Please refer to below article of my publication [.NET Hub](https://medium.com/dotnet-hub):

- [Use Autofac IoC Container in ASP.NET or ASP.NET Core](https://medium.com/dotnet-hub/use-autofac-ioc-container-in-dotnet-or-aspnetcore-autofac-dependency-injection-netcore-ffad19d87163)




Expand Down
4 changes: 3 additions & 1 deletion src/AutofacExamples.Api/AutofacExamples.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Autofac" Version="6.2.0" />
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.1.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.13" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.1.3" />
</ItemGroup>

</Project>
41 changes: 41 additions & 0 deletions src/AutofacExamples.Api/Controllers/TestController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#region Imports
using AutofacExamples.Api.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
#endregion

namespace AutofacExamples.Api.Controllers
{
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
#region Members

private readonly IService _service;
private readonly ILogger<TestController> _logger;

#endregion

#region Ctor

public TestController(IService service, ILogger<TestController> logger)
{
_service = service;
_logger = logger;
}

#endregion

#region Methods

[HttpGet]
public IActionResult Get()
{
var result = _service.Method(0, "");
return Ok(result);
}

#endregion
}
}
39 changes: 0 additions & 39 deletions src/AutofacExamples.Api/Controllers/WeatherForecastController.cs

This file was deleted.

44 changes: 44 additions & 0 deletions src/AutofacExamples.Api/Infrastructure/MyAutofacModule.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#region Imports
using Autofac;
using AutofacExamples.Api.Services;
#endregion

namespace AutofacExamples.Api.Infrastructure
{
/// <summary>
/// Autofac module
/// Configure related services that provide a subsystem.
/// Package optional application features as ‘plug-ins’.
/// Register a number of similar services that are often used together.
/// </summary>
public class MyAutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
//builder.RegisterType<MyService>().As<IService>();

// Transient
builder.RegisterType<MyService>().As<IService>()
.InstancePerDependency();

// Scoped
builder.RegisterType<MyService>().As<IService>()
.InstancePerLifetimeScope();

builder.RegisterType<MyService>().As<IService>()
.InstancePerRequest();


// Singleton
builder.RegisterType<MyService>().As<IService>()
.SingleInstance();



//// Scan an assembly for components
//builder.RegisterAssemblyTypes(typeof(Startup).Assembly)
// .Where(t => t.Name.EndsWith("Service"))
// .AsImplementedInterfaces();
}
}
}
10 changes: 4 additions & 6 deletions src/AutofacExamples.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
#region Imports
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#endregion

namespace AutofacExamples.Api
{
Expand All @@ -18,6 +15,7 @@ public static void Main(string[] args)

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
Expand Down
7 changes: 7 additions & 0 deletions src/AutofacExamples.Api/Services/IService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace AutofacExamples.Api.Services
{
public interface IService
{
string Method(int i, string s);
}
}
10 changes: 10 additions & 0 deletions src/AutofacExamples.Api/Services/MyService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace AutofacExamples.Api.Services
{
public class MyService : IService
{
public string Method(int i, string s)
{
return "My Data";
}
}
}
90 changes: 79 additions & 11 deletions src/AutofacExamples.Api/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,40 +1,37 @@
#region Imports
using Autofac;
using AutofacExamples.Api.Infrastructure;
using AutofacExamples.Api.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#endregion

namespace AutofacExamples.Api
{
public class Startup
{
public IConfiguration Configuration { get; }


public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "AutofacExamples.Api", Version = "v1" });
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
Expand All @@ -55,5 +52,76 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
endpoints.MapControllers();
});
}


/// <summary>
/// Configure Container using Autofac: Register Dependency Injection.
/// This is called AFTER ConfigureServices.
/// So things you register here OVERRIDE things registered in ConfigureServices.
/// You must have the call to `UseServiceProviderFactory(new AutofacServiceProviderFactory())` in Program.cs
/// When building the host or this won't be called.
/// </summary>
/// <param name="builder"></param>
public void ConfigureContainer(ContainerBuilder builder)
{
#region WAY-1 (Autofac Module)

// Add any Autofac modules registrations.
// Configure related services that provide a subsystem.
// Package optional application features as ‘plug-ins’.
// Register a number of similar services that are often used together.

builder.RegisterModule(new MyAutofacModule());
//builder.RegisterModule(new MyAutofacModule2());
//builder.RegisterModule(new MyAutofacModule3());

#endregion


#region WAY-2 (Direct Registration)

// Add any services registrations.
builder.RegisterType<MyService>().As<IService>();

// Transient
builder.RegisterType<MyService>().As<IService>()
.InstancePerDependency();

// Scoped
builder.RegisterType<MyService>().As<IService>()
.InstancePerLifetimeScope();

builder.RegisterType<MyService>().As<IService>()
.InstancePerRequest();

// Singleton
builder.RegisterType<MyService>().As<IService>()
.SingleInstance();

#endregion


#region Diagnostics

// If you want to enable diagnostics, you can do that via a build
// callback. Diagnostics aren't free, so you shouldn't just do this
// by default. Note: since you're diagnosing the container you can't
// ALSO resolve the logger to which the diagnostics get written, so
// writing directly to the log destination is the way to go.
/*
var tracer = new DefaultDiagnosticTracer();
tracer.OperationCompleted += (sender, args) =>
{
Console.WriteLine(args.TraceContent);
};
builder.RegisterBuildCallback(c =>
{
var container = c as IContainer;
container.SubscribeToDiagnostics(tracer);
});
*/

#endregion
}
}
}
15 changes: 0 additions & 15 deletions src/AutofacExamples.Api/WeatherForecast.cs

This file was deleted.

0 comments on commit bce047f

Please sign in to comment.