IUnitOfWork to DomainService constructor using Unity container

72 views Asked by At

I created Silverlight application and I want to realise it via WCF RIA Services. There are 3 projects in my solution:

  1. Data access layer library which contains all db logic and entities. I will use IUnitOfWork interface to communicate with it:

    public interface IUnitOfWork : IDisposable
    {
         IRepository<Customer> Customers { get; }
         IRepository<Product> Products { get; }
         IRepository<Order> Orders { get; }
         void Save();
    }
    
  2. WCF RIA Services project where I created custom DomainService class. Its constructor takes IUnitOfWork interface parameter:

    [EnableClientAccess()]
    public void StoreService : DomainService
    {
         private IUnitOfWork _repository;
         public StoreService(IUnitOfWork repository)
         {
              _repository = repository;
         }
         // ... some methods to query _repository
    }
    
  3. Client project (its written in WPF).

So, I want to use Unity IoC container to path interface implementation into service. I can't understand where need to create custom service factory or something like that and where to register it to be used by system. For example, I know that in ASP.NET MVC there is DefaultControllerFactory class which I need to derive. Then put my IoC bindings in it and then register it in Global.asax.cs file. Can you help me, please. Thanks.

1

There are 1 answers

1
Chui Tey On BEST ANSWER

The DomainService exposes a static property called DomainService.DomainServiceFactory.

You'll need a custom class that implements IDomainServiceFactory

interface IDomainServiceFactory
{
  DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context);
  void ReleaseDomainService(DomainService domainService)
}

I've copied and pasted a blog post from Fredrik Normen how to wire up Unity to DomainService.

public class MyDomainServiceFactory : IDomainServiceFactory
{

    public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context)
    {
        var service = Global.UnityContainer.Resolve(domainServiceType) as DomainService;
        service.Initialize(context);

        return service;
    }


    public void ReleaseDomainService(DomainService domainService)
    {
        domainService.Dispose();
    }
}

In your Global.asax

protected void Application_Start(object sender, EventArgs e)
{
   DomainService.Factory = new MyDomainServiceFactory();

   UnityContainer.RegisterType<StoreService>();
   UnityContainer.RegisterType<IUnitOfWork, UnitOfWorkImpl>();
}