Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
In the realm of .NET development, managing dependencies efficiently is crucial for building scalable, maintainable, and testable applications. Dependency injection (DI) containers play a pivotal role in achieving these goals by facilitating the inversion of control (IoC) principle. Among the plethora of generic hosting mechanism libraries available, Autofac stands out as a feature-rich and extensible framework for .NET.
In this article, we'll embark on a journey to explore Autofac .NET 6, unraveling its features and benefits to showcase practical examples of its usage. Later in this article, we will learn about IronPDF, a PDF generation library from Iron Software. We will also present a use case where Autofac.NET and IronPDF are used together.
Autofac is an open-source IoC container for .NET that provides comprehensive support for dependency injection and component registration in apps like web APIs. Developed by Nicholas Blumhardt and maintained by a dedicated community, Autofac offers a robust and flexible solution for managing object lifetimes, resolving dependencies, and composing application components.
Container Building and Component Registration: You can build containers using Autofac by registering components in the startup class. You can register components using lambdas, types, or pre-built instances.
public class Startup
{
public void ConfigureContainer()
{
var builder = new ContainerBuilder(); // host sub property builder
builder.RegisterInstance(new TaskRepository()).As<ITaskRepository>();
builder.RegisterType<TaskController>();
builder.Register(c => new LogManager(DateTime.Now)).As<ILogger>();
// Scan an assembly for components
builder.RegisterAssemblyTypes(myAssembly).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();
var container = builder.Build();
}
}
public class Startup
{
public void ConfigureContainer()
{
var builder = new ContainerBuilder(); // host sub property builder
builder.RegisterInstance(new TaskRepository()).As<ITaskRepository>();
builder.RegisterType<TaskController>();
builder.Register(c => new LogManager(DateTime.Now)).As<ILogger>();
// Scan an assembly for components
builder.RegisterAssemblyTypes(myAssembly).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();
var container = builder.Build();
}
}
Public Class Startup
Public Sub ConfigureContainer()
Dim builder = New ContainerBuilder() ' host sub property builder
builder.RegisterInstance(New TaskRepository()).As(Of ITaskRepository)()
builder.RegisterType(Of TaskController)()
builder.Register(Function(c) New LogManager(DateTime.Now)).As(Of ILogger)()
' Scan an assembly for components
builder.RegisterAssemblyTypes(myAssembly).Where(Function(t) t.Name.EndsWith("Repository")).AsImplementedInterfaces()
Dim container = builder.Build()
End Sub
End Class
Express Dependencies: Autofac can inject constructor parameters, handle property injection, and method injection.
public class TaskController
{
private ITaskRepository _repository;
private ILogger _logger;
public TaskController(ITaskRepository repository, ILogger logger)
{
this._repository = repository;
this._logger = logger;
}
}
public class TaskController
{
private ITaskRepository _repository;
private ILogger _logger;
public TaskController(ITaskRepository repository, ILogger logger)
{
this._repository = repository;
this._logger = logger;
}
}
Public Class TaskController
Private _repository As ITaskRepository
Private _logger As ILogger
Public Sub New(ByVal repository As ITaskRepository, ByVal logger As ILogger)
Me._repository = repository
Me._logger = logger
End Sub
End Class
Flexible Module System: Autofac modules strike a balance between XML configuration and code-based registrations. You can specify complex registrations in code or change deployment-time behavior using XML.
public class CarTransportModule : Module
{
public bool ObeySpeedLimit { get; set; }
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<Car>().As<IVehicle>();
if (ObeySpeedLimit)
builder.RegisterType<SaneDriver>().As<IDriver>();
else
builder.RegisterType<CrazyDriver>().As<IDriver>();
}
}
public class CarTransportModule : Module
{
public bool ObeySpeedLimit { get; set; }
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<Car>().As<IVehicle>();
if (ObeySpeedLimit)
builder.RegisterType<SaneDriver>().As<IDriver>();
else
builder.RegisterType<CrazyDriver>().As<IDriver>();
}
}
Public Class CarTransportModule
Inherits Module
Public Property ObeySpeedLimit() As Boolean
Protected Overrides Sub Load(ByVal builder As ContainerBuilder)
builder.RegisterType(Of Car)().As(Of IVehicle)()
If ObeySpeedLimit Then
builder.RegisterType(Of SaneDriver)().As(Of IDriver)()
Else
builder.RegisterType(Of CrazyDriver)().As(Of IDriver)()
End If
End Sub
End Class
Simple Extension Points: Autofac provides activation events to customize component activation or release.
var builder = new ContainerBuilder();
builder.RegisterType<Listener>().As<IListener>().OnActivated(e => e.Instance.StartListening());
builder.RegisterType<Processor>().OnActivating(e => e.Instance.Initialize());
var container = builder.Build();
var builder = new ContainerBuilder();
builder.RegisterType<Listener>().As<IListener>().OnActivated(e => e.Instance.StartListening());
builder.RegisterType<Processor>().OnActivating(e => e.Instance.Initialize());
var container = builder.Build();
Dim builder = New ContainerBuilder()
builder.RegisterType(Of Listener)().As(Of IListener)().OnActivated(Function(e) e.Instance.StartListening())
builder.RegisterType(Of Processor)().OnActivating(Function(e) e.Instance.Initialize())
Dim container = builder.Build()
Let's explore some practical examples to illustrate the usage of Autofac.NET:
public class Program
{
public static void Main()
{
// Setting up Autofac container
var builder = new ContainerBuilder();
// Registering types manually
builder.RegisterType<MyService>().As<IMyService>();
// Registering types using assembly scanning
builder.RegisterAssemblyTypes(typeof(MyAssembly).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
// Registering modules
builder.RegisterModule(new MyModule());
// Building the container
var container = builder.Build();
// Resolving dependencies
using (var scope = container.BeginLifetimeScope())
{
var service = scope.Resolve<IMyService>();
service.DoSomething();
}
}
}
public class Program
{
public static void Main()
{
// Setting up Autofac container
var builder = new ContainerBuilder();
// Registering types manually
builder.RegisterType<MyService>().As<IMyService>();
// Registering types using assembly scanning
builder.RegisterAssemblyTypes(typeof(MyAssembly).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
// Registering modules
builder.RegisterModule(new MyModule());
// Building the container
var container = builder.Build();
// Resolving dependencies
using (var scope = container.BeginLifetimeScope())
{
var service = scope.Resolve<IMyService>();
service.DoSomething();
}
}
}
Public Class Program
Public Shared Sub Main()
' Setting up Autofac container
Dim builder = New ContainerBuilder()
' Registering types manually
builder.RegisterType(Of MyService)().As(Of IMyService)()
' Registering types using assembly scanning
builder.RegisterAssemblyTypes(GetType(MyAssembly).Assembly).Where(Function(t) t.Name.EndsWith("Repository")).AsImplementedInterfaces()
' Registering modules
builder.RegisterModule(New MyModule())
' Building the container
Dim container = builder.Build()
' Resolving dependencies
Using scope = container.BeginLifetimeScope()
Dim service = scope.Resolve(Of IMyService)()
service.DoSomething()
End Using
End Sub
End Class
In this section, we've demonstrated the practical implementation of Autofac.NET for dependency injection. From manual registration to assembly scanning and module-based registration, we've shown the flexibility Autofac offers in managing dependencies. By utilizing these techniques, developers can streamline their application's dependency injection process, enhancing maintainability and scalability.
Autofac comes with an MIT License which is free for use for development and commercial purposes.
IronPDF is a robust C# PDF library designed to provide a comprehensive solution for managing PDFs in .NET projects. Whether your needs involve creating, editing, exporting, securing, loading, or manipulating PDF documents, IronPDF has the tools you need. Here are some of its standout features and applications:
Now let's see a practical example with these two libraries.
First, let's create a Visual Studio console application
Provide the project name and location.
For the next step, select the required .NET version and click Create.
Then install the IronPDF library from NuGet Package from Visual Studio Package Manager
Install Autofac from NuGet Package from Visual Studio Package Manager
using Autofac;
using CacheManager.Core;
using IronPdf;
using System.Reflection;
namespace IronPdfDemos
{
public class AutoFac
{
public static void Execute()
{
// Instantiate Cache and ChromePdfRenderer
var renderer = new ChromePdfRenderer();
var cache = CacheFactory.Build("ironPdfAutofac", settings =>
{
settings.WithDictionaryHandle();
});
// Prepare HTML content
var content = "<h1>Demonstrate Autofac with IronPDF</h1>";
content += "<p>This is an illustration of using Autofac for dependency injection and IronPDF for generating PDF documents.</p>";
content += "<h2>Setting up Autofac container</h2>";
// Setting up Autofac container
var builder = new ContainerBuilder();
content += "<p>var builder = new ContainerBuilder();</p>";
content += "<h2>Registering types manually</h2>";
// Registering types manually
builder.RegisterType<MyService>().As<IMyService>();
content += "<p>builder.RegisterType<MyService>().As<IMyService();</p>";
content += "<h2>Registering types using assembly scanning</h2>";
// Registering types using assembly scanning
builder.RegisterAssemblyTypes(typeof(AutoFac).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
content += "<p>builder.RegisterAssemblyTypes(typeof(AutoFac).Assembly).Where(t => t.Name.EndsWith(\"Repository\")).AsImplementedInterfaces();</p>";
content += "<h2>Registering modules</h2>";
// Registering modules
builder.RegisterModule(new MyModule());
content += "<p>builder.RegisterModule(new MyModule());</p>";
content += "<h2>Building the container</h2>";
// Building the container
var container = builder.Build();
content += "<p>var container = builder.Build();</p>";
content += "<h2>Resolving dependencies</h2>";
// Resolving dependencies
using (var scope = container.BeginLifetimeScope())
{
var service = scope.Resolve<IMyService>();
service.DoSomething();
}
content += "<p>var service = scope.Resolve<IMyService();</p>";
// Create a PDF from the HTML string using C#
var pdf = renderer.RenderHtmlAsPdf(content);
// Export to a file or Stream
pdf.SaveAs("autofac.pdf");
Console.WriteLine("We are done...");
Console.ReadKey();
}
}
internal interface IMyService
{
void DoSomething();
}
internal class MyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
// Register module dependencies here
}
}
internal class MyService : IMyService
{
public void DoSomething()
{
Console.WriteLine("DoSomething");
}
}
}
using Autofac;
using CacheManager.Core;
using IronPdf;
using System.Reflection;
namespace IronPdfDemos
{
public class AutoFac
{
public static void Execute()
{
// Instantiate Cache and ChromePdfRenderer
var renderer = new ChromePdfRenderer();
var cache = CacheFactory.Build("ironPdfAutofac", settings =>
{
settings.WithDictionaryHandle();
});
// Prepare HTML content
var content = "<h1>Demonstrate Autofac with IronPDF</h1>";
content += "<p>This is an illustration of using Autofac for dependency injection and IronPDF for generating PDF documents.</p>";
content += "<h2>Setting up Autofac container</h2>";
// Setting up Autofac container
var builder = new ContainerBuilder();
content += "<p>var builder = new ContainerBuilder();</p>";
content += "<h2>Registering types manually</h2>";
// Registering types manually
builder.RegisterType<MyService>().As<IMyService>();
content += "<p>builder.RegisterType<MyService>().As<IMyService();</p>";
content += "<h2>Registering types using assembly scanning</h2>";
// Registering types using assembly scanning
builder.RegisterAssemblyTypes(typeof(AutoFac).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();
content += "<p>builder.RegisterAssemblyTypes(typeof(AutoFac).Assembly).Where(t => t.Name.EndsWith(\"Repository\")).AsImplementedInterfaces();</p>";
content += "<h2>Registering modules</h2>";
// Registering modules
builder.RegisterModule(new MyModule());
content += "<p>builder.RegisterModule(new MyModule());</p>";
content += "<h2>Building the container</h2>";
// Building the container
var container = builder.Build();
content += "<p>var container = builder.Build();</p>";
content += "<h2>Resolving dependencies</h2>";
// Resolving dependencies
using (var scope = container.BeginLifetimeScope())
{
var service = scope.Resolve<IMyService>();
service.DoSomething();
}
content += "<p>var service = scope.Resolve<IMyService();</p>";
// Create a PDF from the HTML string using C#
var pdf = renderer.RenderHtmlAsPdf(content);
// Export to a file or Stream
pdf.SaveAs("autofac.pdf");
Console.WriteLine("We are done...");
Console.ReadKey();
}
}
internal interface IMyService
{
void DoSomething();
}
internal class MyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
// Register module dependencies here
}
}
internal class MyService : IMyService
{
public void DoSomething()
{
Console.WriteLine("DoSomething");
}
}
}
Imports Autofac
Imports CacheManager.Core
Imports IronPdf
Imports System.Reflection
Namespace IronPdfDemos
Public Class AutoFac
Public Shared Sub Execute()
' Instantiate Cache and ChromePdfRenderer
Dim renderer = New ChromePdfRenderer()
Dim cache = CacheFactory.Build("ironPdfAutofac", Sub(settings)
settings.WithDictionaryHandle()
End Sub)
' Prepare HTML content
Dim content = "<h1>Demonstrate Autofac with IronPDF</h1>"
content &= "<p>This is an illustration of using Autofac for dependency injection and IronPDF for generating PDF documents.</p>"
content &= "<h2>Setting up Autofac container</h2>"
' Setting up Autofac container
Dim builder = New ContainerBuilder()
content &= "<p>var builder = new ContainerBuilder();</p>"
content &= "<h2>Registering types manually</h2>"
' Registering types manually
builder.RegisterType(Of MyService)().As(Of IMyService)()
content &= "<p>builder.RegisterType<MyService>().As<IMyService();</p>"
content &= "<h2>Registering types using assembly scanning</h2>"
' Registering types using assembly scanning
builder.RegisterAssemblyTypes(GetType(AutoFac).Assembly).Where(Function(t) t.Name.EndsWith("Repository")).AsImplementedInterfaces()
content &= "<p>builder.RegisterAssemblyTypes(typeof(AutoFac).Assembly).Where(t => t.Name.EndsWith(""Repository"")).AsImplementedInterfaces();</p>"
content &= "<h2>Registering modules</h2>"
' Registering modules
builder.RegisterModule(New MyModule())
content &= "<p>builder.RegisterModule(new MyModule());</p>"
content &= "<h2>Building the container</h2>"
' Building the container
Dim container = builder.Build()
content &= "<p>var container = builder.Build();</p>"
content &= "<h2>Resolving dependencies</h2>"
' Resolving dependencies
Using scope = container.BeginLifetimeScope()
Dim service = scope.Resolve(Of IMyService)()
service.DoSomething()
End Using
content &= "<p>var service = scope.Resolve<IMyService();</p>"
' Create a PDF from the HTML string using C#
Dim pdf = renderer.RenderHtmlAsPdf(content)
' Export to a file or Stream
pdf.SaveAs("autofac.pdf")
Console.WriteLine("We are done...")
Console.ReadKey()
End Sub
End Class
Friend Interface IMyService
Sub DoSomething()
End Interface
Friend Class MyModule
Inherits Module
Protected Overrides Sub Load(ByVal builder As ContainerBuilder)
' Register module dependencies here
End Sub
End Class
Friend Class MyService
Implements IMyService
Public Sub DoSomething() Implements IMyService.DoSomething
Console.WriteLine("DoSomething")
End Sub
End Class
End Namespace
Let’s break down the code snippet you provided:
ChromePdfRenderer Setup:
ChromePdfRenderer
instance for rendering PDFs.HTML Content Preparation:
content
variable is an HTML string that will be used to generate the PDF.<h1>
tag with the title "Demonstrate Autofac with IronPDF".Setting Up Autofac Container:
ContainerBuilder
named builder
.Registering Types Manually:
MyService
as an implementation of the IMyService
interface.Registering Types Using Assembly Scanning:
AutoFac
type.Registering Modules:
MyModule
.Building the Container:
builder.Build()
method.Resolving Dependencies:
using (var scope = container.BeginLifetimeScope())
), it resolves an instance of IMyService
.DoSomething
method is called on the resolved service.ChromePdfRenderer
.IronPDF requires a license key. Place the license key in the appSettings.json
file as shown below.
{
"IronPdf.License.LicenseKey": "The Key Here"
}
In conclusion, Autofac.NET stands as a robust and feature-rich dependency injection container for .NET, empowering developers to build modular, maintainable, and extensible applications. Whether you're developing desktop applications, web services, or cloud-native solutions, Autofac offers a reliable foundation for managing dependencies and promoting best practices in .NET development.
IronPDF is a versatile and feature-rich library to generate, edit, and read PDF documents. Together with the IronPDF library from Iron Software to read and generate PDF documents, developers can gain advanced skills to develop modern applications.
9 .NET API products for your office documents