.Net RIA Services: DomainService Needs a Parameterless Constructor?

﹥>﹥吖頭↗ 提交于 2019-12-03 14:30:48

Since you have a DomainService with a parameter in its ctor, and more generally needs to be constructed through some sort of IoC container or dependency injection system, you'll need to provide an app-level domain service factory. Your factory is then responsible for instantiating the domain service (and disposing it), and it can do so by calling into another API, such as Unity in your case.

Here's a basic example:

In Global.asax.cs of your app, add the following:

public class Global : HttpApplication {

    static Global() {
        DomainService.Factory = new MyAppDomainServiceFactory();
    }
}

internal sealed class MyAppDomainServiceFactory : IDomainServiceFactory {

    public DomainService CreateDomainService(Type domainServiceType,
                                             DomainServiceContext context) {
        DomainService ds = ... // code to create a service, or look it up
                               // from a container

        if (ds != null) {
            ds.Initialize(context);
        }
        return ds;
    }

    public void ReleaseDomainService(DomainService domainService) {
        // any custom logic that must be run to dispose a domain service
        domainService.Dispose();
    }
}

Hope that helps!

@Brien, I assume the 'IUserService' depends on IUnitOfWork, where the IUnitOfWork is the DashboardEntities ?

Like this UserRepository:

public class UserRepository : BaseRepository<User>, IUserRepository
{
    protected BaseRepository(IUnitOfWork unitOfWork)
    {
    }

    ...
}

And this IUnitOfWork:

public partial class DashboardEntities : ObjectContext, IUnitOfWork
{
    public const string ConnectionString = "name=DashboardEntities";
    public const string ContainerName = "DashboardEntities";

    public DashboardEntities()
        : base(ConnectionString, ContainerName)
    {
        this.ContextOptions.LazyLoadingEnabled = true;
    }

    ...
}

I'm using this design. One thing I noticed is that the DashboardEntities class is created more than once. The first time it's created by Unity (and will only be created once because it's declared as an Singleton in the Unity Configuration).

But the next time, it seems that a new DashboardEntities class is created during the initialize from the DomainService (DashboardService) ? This is no big deal because the DomainService will not use this ObjectContext, it will use the ObjectContext which is injected by Unity in the Repositories.

Can someone confirm this design or show some more light on this issue ?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!