依赖注入一起使用

时间:2013-10-19 10:18:01

标签: model-view-controller dependency-injection structuremap autofac

我有一个mvc项目。我在成员资格提供程序中使用Autofac In Entity Access Layer和StructureMap。

我可以在单个mvc项目中一起使用Autofac和structuremap吗?

日Thnx

1 个答案:

答案 0 :(得分:0)

我想您在项目中使用ASP.NET MVC。然后,您只需要实现ASP.NET MVC IDependencyResolver接口,该接口只包含两个方法,如下所示:

public interface IDependencyResolver
{
    object GetService(Type serviceType);
    IEnumerable<object> GetServices(Type serviceType);
}

您的实现应该在其构造函数中包含两个参数:Autofac依赖项解析程序和StructureMap依赖项解析程序。它看起来像这样:

public class CombinedDependencyResolver : IDependencyResolver
{
    private readonly AutofacDependencyResolver _autofacDependencyResolver;
    private readonly StructureMapDependencyResolver _structureMapDependencyResolver;

    public CombinedDependencyResolver(AutofacDependencyResolver autofacDependencyResolver, StructureMapDependencyResolver structureMapDependencyResolver)
    {
        _autofacDependencyResolver = autofacDependencyResolver;
        _structureMapDependencyResolver = structureMapDependencyResolver;
    }

    public object GetService(Type serviceType)
    {
        // your logic here
        _structureMapDependencyResolver.GetService(serviceType);
        _autofacDependencyResolver.GetService(serviceType);
        return new object();
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        // your logic here
        return null;
    }
}

然后根据您的逻辑实现IDependencyResolver的方法,并从AutofacDependencyResolver或StructureMapDependencyResolver解析依赖关系。