Интеграция StructureMap и Entity Framework - PullRequest
0 голосов
/ 05 августа 2011

у меня

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 Exception Code:  202
No Default Instance defined for 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, Culture=neutral, PublicKeyToken=null

on the Controllerfactory class

Line 13:         protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
Line 14:         {
Line 15:             return ObjectFactory.GetInstance(controllerType) as IController;
Line 16:         }
Line 17:     }

Source File: E:\HCPanel\HCPanel.Web\IoCControllerFactory.cs    Line: 15

1 Ответ

1 голос
/ 05 августа 2011

Ответ от: StructureMap Автоматическая регистрация универсальных типов с использованием Scan

Advanced StructureMap: подключение реализаций для открытия универсальных типов

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();
                   });
});
...