【问题标题】:Integrating StructureMap and Entity Framework集成 StructureMap 和实体框架
【发布时间】:2011-10-20 13:19:48
【问题描述】:

我有

public interface IRepository<T> where T : EntityBase
{
}

及其实现,EfRepository 就像

public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
{
    ....
}

我的 MVC 控制器工厂类:

 public class IoCControllerFactory: DefaultControllerFactory
{
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return ObjectFactory.GetInstance(controllerType) as IController;
    }
}

所以在 autofac 中我可以这样做:

builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).
        InstancePerHttpRequest();

我怎样才能在 StructureMap 中做同样的事情?我不想生成所有存储库类并声明如下:

ObjectFactory.Initialize(x => {
    x.For<IRoleRepository>().Use<RoleRepository>();
    x.For<IWebSiteRepository>().Use<WebSiteRepository>();
    .....
}

我试过了,但没有运气

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        //      BootStrapper.ConfigureDependencies();
        ObjectFactory.Initialize(x =>
        {

            x.For<IDatabaseFactory>().Use<DatabaseFactory>();

            x.Scan(y =>
            {
               y.AssemblyContainingType(typeof(IRepository<>));
                y.ConnectImplementationsToTypesClosing(typeof(IRepository<>)).
                    OnAddedPluginTypes(z => z.HybridHttpOrThreadLocalScoped());

            });

            x.For<IUnitOfWork>().Use<EFUnitOfWork>();

            //services

            x.For<ICategoryService>().Use<CategoryService>();

        });
        try
        {
            ObjectFactory.AssertConfigurationIsValid();
        }
        catch (StructureMapConfigurationException ex)
        {
            string msg = ex.ToString();
            throw;
        }

        ControllerBuilder.Current.SetControllerFactory(new IoCControllerFactory());
    }

我的服务等级:

 public partial class CategoryService : ICategoryService
{
    private readonly IRepository<Category> _categoryRepository;      
    private readonly IUnitOfWork _uow;

    public CategoryService(IRepository<Category> categoryRepository, IUnitOfWork uow)
    {
        this._categoryRepository = categoryRepository;        
        this._uow = uow;
    }   

    public IList<Category> GetAllCategories(Func<Category, bool> expression)
    {
        return _categoryRepository.FindMany(expression).ToList();
    }

}

总是报错:

StructureMap 异常代码:202 没有为 PluginFamily IoC.Repository.IRepository`1[[IoC.Model.Catalog.Category, IoC.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], IoC.Repository, Version=1.0 定义默认实例.0.0,文化=中性,PublicKeyToken=null 在 Controllerfactory 类上 第 13 行:受保护的覆盖 IController GetControllerInstance(RequestContext requestContext, Type controllerType) 第 14 行:{ 第 15 行:返回 ObjectFactory.GetInstance(controllerType) 作为 IController; 第 16 行:} 第 17 行:} 源文件:E:\HCPanel\HCPanel.Web\IoCControllerFactory.cs 行:15

【问题讨论】:

    标签: .net entity-framework structuremap


    【解决方案1】:

    答案来自: StructureMap Auto registration for generic types using Scan

    Advanced StructureMap: connecting implementations to open generic types

    ObjectFactory.Initialize(x =>
    {
         x.Scan(cfg => 
                      {
                          cfg.AssemblyContainingType(typeof(IRepository<>));
                          cfg.ConnectImplementationsToTypesClosing(typeof(IRepository<>))
                             .OnAddedPluginTypes(y => y.HybridHttpOrThreadLocalScoped())
                      });
    });
    

    编辑:

    试试:

    ObjectFactory.Initialize(x =>
    {
         x.Scan(cfg =>
                       {
                           cfg.RegisterConcreteTypesAgainstTheFirstInterface();
                       });
    });
    

    【讨论】:

    • 这很奇怪,同样的错误。不知道为什么。我使用的是 2.6.2 版
    • @Nam - 你能给我一个你遇到困难的小示例解决方案吗,phillip.haydon [at] gmail.com,我没有任何问题让它工作,但也许我可以在工作状态下查看并发回给您。
    • 非常感谢,现在它正在工作,奇怪的是我尝试了一整天但总是失败。再说一次,你对我保持冷静真是太好了。快乐的一天。
    • 顺便问一下,structuremap可以像autofac一样自动生成所有的repository类吗? nopcommerce.codeplex.com 项目使用 Autofac,它不需要创建单个 IRepository 和具体类。说像 ICategoryRepository 和 CategoryRepository
    • @Nam - 哇,那个项目中的 DependencyRegistrar 类太糟糕了。我在家里使用 Autofac,在工作中使用 StructureMap,使用 SM,我们在存储库项目中创建了一个注册表,它只扫描该 1 个程序集以查找以“存储库”结尾的任何内容,并使用上面的方法:“RegisterConcreteTypesAgainstTheFirstInterface”,将它们全部注册。我们没有通用的“IRepository”,因为我相信拥有这样的接口会强制您的所有存储库公开不需要的方法。 (例如,某些存储库不应该删除)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多