How to use Autofac in C#

Autofac is an addictive Inversion of Control container for .NET Core, ASP.NET Core, .NET 4.5.1+, Universal Windows apps, and more

Step 1: Create a new project called AutofacDemo

autofacStep 2: Right click on your project select Manage NuGet Packages -> Search autofac -> install

install autofacStep 3: Create an interface is IConnection

public interface IConnection
{
    void Connect();
    void Command(string command);
}

Create MySqlConnection inherit from IConnection, then implement Command, Connect method

public class MySqlConnection : IConnection
{
    public void Command(string command)
    {
        Console.Write("Execute MySql command: {0}", command);
    }

    public void Connect()
    {
        Console.WriteLine("Connect to MySql Server...");
    }
}

Create SqlConnection inherit from IConnection

public class SqlConnection : IConnection
{
    public void Command(string command)
    {
        Console.Write("Execute Sql command: {0}", command);
    }

    public void Connect()
    {
        Console.WriteLine("Connect to Sql Server...");
    }
}

Create AppService class to control the instance you want to create

public static class AppService
{
    static IContainer Container { get; set; }
    static AppService()
    {
        ContainerBuilder builder = new ContainerBuilder();
        builder.RegisterType<MySqlConnection>().As<IConnection>();//Change your instance you want to create
        Container = builder.Build();
    }

    public static IConnection Connection => Container.Resolve<IConnection>();
}

You can call Connect, Command method in Main method

class Program
{
    static void Main(string[] args)
    {
        AppService.Connection.Connect();
        AppService.Connection.Command("Insert");
        Console.ReadLine();//Wait
    }
}

You can easily to change the instance you want to create, we don't need to change code in the Main method

builder.RegisterType<SqlConnection>().As<IConnection>();//Change your instance you want to create

Press F5 to run your program

autofac

Related Posts