Custom Domain Service Factory

Parameterized constructors are not allowed in WCF RIA domain service, however your object model may requires to have constructor with arguments. For example EmployeeService (in this example) is WCF RIA Domain Service which requires Authentication and have constructor with authenticated User instance as parameter. The activate the service in such scenario you need to provide your own custom domain factory calls and plug the factory in Application_Start event of Global.aspx.

Sample Employee Service class

[EnableClientAccess()]
[RequiresAuthentication()]
public class EmployeeService : DomainService
{
        
    public EmployeeService(User user)
    {
            
    }
    //......
        
}

Custom Domain service factory

internal sealed class DomainServiceFactory : IDomainServiceFactory
{
    private IDomainServiceFactory _defaultFactory;


    public DomainServiceFactory(IDomainServiceFactory defaultFactory)
    {
        _defaultFactory = defaultFactory;
    }

    public static void Setup()
    {
        if (!(DomainService.Factory is DomainServiceFactory))
        {
            DomainService.Factory = new DomainServiceFactory(DomainService.Factory);
        }
    }

    public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context)
    {
        if (domainServiceType == typeof(EmployeeService))
        {
            DomainServiceContext authServiceContext =
                new DomainServiceContext(context, DomainOperationType.Query);
            AuthenticationService authService =
                (AuthenticationService)_defaultFactory.CreateDomainService(typeof(AuthenticationService), authServiceContext);
            User user = authService.GetUser();

            DomainService domainService = (DomainService)Activator.CreateInstance(domainServiceType, user);
            domainService.Initialize(context);
            return domainService;
        }
        else
        {
            return _defaultFactory.CreateDomainService(domainServiceType, context);
        }
    }

    public void ReleaseDomainService(DomainService domainService)
    {
        if (domainService is EmployeeService)
        {
            domainService.Dispose();
        }
        else
        {
            _defaultFactory.ReleaseDomainService(domainService);
        }
    }
}

Setup Domain service factory

protected void Application_Start(object sender, EventArgs e)
{
    DomainServiceFactory.Setup();

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s