vendredi 18 août 2017

Autofac WCF injection on reflection

I have N validators on my aplication but a client doesn't use all validators, I got by procedure all classes that my current client will need to instantiate.

My Business layer:

public class MyClass
{
    public void MyMethod(int idClient)
    {
        //This array is returned by a procedure passing idClient
        string[] validatorsName = { "ValidatorName", "ValidatorName2" };

        foreach (string name in validatorsName)
        {

            IValidator validator = (IValidator)Activator.CreateInstance(Type.GetType(name));
            //Error. I need pass the INameDB;

            validator.Process();
        }
    }
}

My Interface:

public interface IValidator
{
    void Process();
}

The Validators:

public class ValidatorName : IValidator
{
    INameDB nameDB;

    public ValidatorName(INameDB nameDB)
    {
        this.nameDB = nameDB;
    }

    public void Process()
    {
        nameDB.AnyThing(pedidoId);
    }
}

public class ValidatorName2 : IValidator
{
    INameDB2 nameDB;

    public ValidatorName(INameDB2 nameDB)
    {
        this.nameDB = nameDB;
    }

    public void Process()
    {
        nameDB.AnyThing2(pedidoId);
    }
}

public class ValidatorName3 : IValidator
{
    INameDB2 nameDB;

    public ValidatorName(INameDB2 nameDB)
    {
        this.nameDB = nameDB;
    }

    public void Process()
    {
        nameDB.AnyThing2(pedidoId);
    }
}

On Global, I could register all validators and with the IList<IValidator>, so I would remove from the list the validators that I will not need.

 string[] validatorsName = { "ValidatorName", "ValidatorName2" };
 validators = validators .Where(p => validatorsName .Contains(p.GetType().Name)).ToList();

but I have a lot of classes, it would register this no need.

My Global:

public class Global : System.Web.HttpApplication
{

    protected void Application_Start(object sender, EventArgs e)
    {
        ContainerBuilder builder = new ContainerBuilder();
        builder.RegisterType<NameDB>().As<INameDB>();
        builder.RegisterType<NameDB2>().As<INameDB2>();

        //builder.RegisterType<ValidatorName1>().As<IValidator>();
        //builder.RegisterType<ValidatorName2>().As<IValidator>();
        //builder.RegisterType<ValidatorName3>().As<IValidator>();

        AutofacHostFactory.Container = builder.Build();
        //AutofacHostFactory.Container.Resolve<IList<IValidator>>();
    }
}

My question is how can I detect the interface INameDB or INameDB2, get the instance on Autofac and use on Activator.CreateInstance?

Thanks.





Aucun commentaire:

Enregistrer un commentaire