views:

337

answers:

1

Hi,

I need to write a test layer to Test my WCF RIA Domain Service layer which is build on top of Entity Framework context. I have come across some patterns which suggest to use a repository and then use the Domain Service factory to intilize the domain service with a repository instance to use. One of the sample which fits the requirement is explained here on Vijay's blog(http://blogs.msdn.com/vijayu/archive/2009/06/08/unit-testing-business-logic-in-net-ria-services.aspx). The problem with this implementation is that it initilize the repository only for a specific Domain Object e.g. Customer/Product but it provides no way to create a repository which can return any object which i would like to return.

Please suggest what is the right way of doing this and whether it is possible or not.

Thanks in advance,

Manoj

A: 

I got around this issue by extending the sample with a RepositoryCollection object, which automatically instantiates LinqToSqlRepositories as needed, and also allows the insertion of mock/stub repositories manually for unit testing.

public class RepositoryCollection : IDisposable
{
    private Dictionary<Type, object> _repositories = new Dictionary<Type, object>();
    private DataContext _context;

    public RepositoryCollection() { }

    public RepositoryCollection(DataContext context)
    {
        _context = context;
    }

    public IRepository<T> Get<T>() where T : class
    {
        if(!_repositories.ContainsKey(typeof(T)))
            _repositories.Add(typeof(T), new LinqToSqlRepository<T>(_context));

        return _repositories[typeof(T)] as IRepository<T>;
    }

    public RepositoryCollection Insert<T>(IRepository<T> repository) where T : class
    {
        _repositories[typeof(T)] = repository;
        return this;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public void SubmitChanges()
    {
        if (_context != null)
            _context.SubmitChanges();
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if(_context != null)
                _context.Dispose();
        }
    }
}

Then, in your domain service, you use it like so:

private RepositoryCollection _repositoryCollection;

public MyDomainService(RepositoryCollection repositoryCollection = null)
{
    _repositoryCollection = repositoryCollection ?? new RepositoryCollection(new MyDataContext());
}

public IQueryable<Customer> GetCustomers()
{
    return _repositoryCollection.Get<Customer>().Query();
}

public IQueryable<Product> GetProducts()
{
    return _repositoryCollection.Get<Product>().Query();
}

.. other methods go here ...
Marty Dill