Neo Neo - 17 days ago 6
C# Question

how to implement autofac dependency injection with parameter in constructor or with any condition?

Before using any dependency injection
I'm using simple
interface
to make a
loosely coupled code
like below -

Program.cs

class Program
{
static void Main(string[] args)
{
Customer obj = new Customer(new OracleData());
obj.Add();
}
}


Customer.cs

public class Customer
{
private Idata iobj;
public Customer(Idata newiobj)
{
iobj = newiobj;
}
public void Add()
{
iobj.AddData();
}
}


OracleData.cs

public class OracleData : Idata
{
public void AddData()
{
throw new NotImplementedException();
}
}


SQLData.cs

public class SQLData : Idata
{
public void AddData()
{
throw new NotImplementedException();
}
}


Idata.cs

public interface Idata
{
void AddData();
}


Now I tried this using
Autofac
DI library -
I wonder it always its last injected class object , how to set resolve object using constructor or with any condition?

code using Autofac DI -

static void Main(string[] args)
{

var builder = new ContainerBuilder();
builder.RegisterType<Customer>();
builder.RegisterType<OracleData>().As<Idata>();
builder.RegisterType<SQLData>().As<Idata>();
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
var app = scope.Resolve<Idata>();
app.AddData();
}

//commented
//Customer obj = new Customer(new OracleData());
//obj.Add();
}

Answer

You if you need to define which implementation you will use at the entry point you can do something like this:

    static void Main(string[] args)
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<Customer>();

        if(args[0] == "oracle")
            builder.RegisterType<OracleData>().As<Idata>();
        else
            builder.RegisterType<SQLData>().As<Idata>();

        var container = builder.Build();

        using (var scope = container.BeginLifetimeScope())
        {
            var app = scope.Resolve<Idata>();
            app.AddData();
        }

        //commented
        //Customer obj = new Customer(new OracleData());
        //obj.Add();
    }
Comments