mardi 25 décembre 2018

Autofac - Register for Transaction

Lets start with my architech. I will try to simplify my code as much as I can. If I totally mixed up, please warn me.

IUnitOfWork

public interface IUnitOfWork<T> : IDisposable
{
    IEntityRepository<T> Repository { get; }
    void Commit();
}

UnitOfWork

public class UnitOfWork<T> : IUnitOfWork<T>
{
    private IDbConnection _Connection;
    private IDbTransaction _Transaction;

    public IRepository<T> Repository { get; private set; }

    public UnitOfWork(IDbConnection Connection, IRepository<T> Repository)
    {
        _Connection = Connection;
        this.Repository = Repository;
         _Transaction = _Connection.BeginTransaction();
    }
}

RepositoryBase

public abstract class RepositoryBase<T> : IRepository<T>
{
    protected IDbTransaction Transaction;
    protected IDbConnection Connection { get { return Transaction.Connection; } }

    public RepositoryBase(IDbTransaction transaction)
    {
        Transaction = transaction;
    }
}

TestDAL

public class TestDAL : RepositoryBase<Test>, ITestDAL
{
    public DpTestDAL(IDbTransaction transaction) : base(transaction) {}
}

TestService (BLL)

public class TestService : ITestService
{
    private IUnitOfWork<Test> uow;
    public TestService(IUnitOfWork<Test> unitOfWork)
    {
        uow = unitOfWork;
    }
    public List<Test> GetAll()
    {
        return uow.Repository.GetAll().ToList();
    }
}

And my autofac configurations.

builder.RegisterType<TestService>().As<ITestService>();
builder.RegisterType(typeof(OracleConnection)).As(typeof(IDbConnection)).InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(RepositoryBase<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(UnitOfWork<>)).As(typeof(IUnitOfWork<>)).InstancePerDependency();
//builder.RegisterType(typeof(OracleTransaction)).As(typeof(IDbTransaction)).InstancePerLifetimeScope();

I am newbie this kind of architect and try to something my self. Please tell me if there is something wrong or totally wrong.

My problem is, I need to pass the IDbTransaction to data acess classess contructor. When I do not register IDbTransaction interface, exception is "could not resolve parameter", when I try to register with OracleTransaction the exception is "OracleTransaction" do not has a public contructor. Where did I mixed up?

Aucun commentaire:

Enregistrer un commentaire