MVC5中的结构图

时间:2015-02-03 10:36:59

标签: dependency-injection structuremap objectfactory

我在MVC5中使用了结构图3.1.2.138。 在我的IoC-class中,我试图使用Objectfactory,但它声明Objectfactory已经过时了,我应该使用Container,但我找不到一种方法来使这项工作。

public static IContainer Initialize() {
        var BS_WebDataContextConnectionString = "Data Source=xxx;Initial Catalog=xxx;Integrated Security=True;MultipleActiveResultSets=True";

        ObjectFactory.Initialize(x =>
            {
                x.Scan(scan =>
                    {
                        scan.Assembly(Assembly.GetCallingAssembly());
                        scan.WithDefaultConventions();
                    });

                //DataContext
                x.For<iBS_WebDataContext>().Use<BS_WebDataContext>()
                    .Ctor<string>("connectionString")
                    .Is(BS_WebDataContextConnectionString);

                //Repositories
                x.For<IReadOnlyEvidenceTypeRepository>().Use<EF6ReadOnlyEvidenceTypeRepository>();
                x.For<IReadOnlyStatusCategoryRepository>().Use<EF6ReadOnlyStatusCategoryRepository>();



                //Services
                x.For<IEvidenceTypeService>().Use<EvidenceTypeService>();
                x.For<IStatusCategoryService>().Use<StatusCategoryService>();


            });
        return ObjectFactory.Container;

}

有人能举例说明如何转换为容器方式吗?

1 个答案:

答案 0 :(得分:0)

它会像这样完成(包括将配置移动到注册表中以保持其良好和整洁。

<强> WebsiteRegistry.cs

public class WebsiteRegistry : Registry
{
    public WebsiteRegistry()
    {
        x.Scan(scan =>
        {
            scan.Assembly(Assembly.GetCallingAssembly());
            scan.WithDefaultConventions();
        });

        //DataContext
        var BS_WebDataContextConnectionString = "Data Source=xxx;Initial Catalog=xxx;Integrated Security=True;MultipleActiveResultSets=True";
        x.For<iBS_WebDataContext>().Use<BS_WebDataContext>().Ctor<string>("connectionString").Is(BS_WebDataContextConnectionString);

        //Repositories
        x.For<IReadOnlyEvidenceTypeRepository>().Use<EF6ReadOnlyEvidenceTypeRepository>();
        x.For<IReadOnlyStatusCategoryRepository>().Use<EF6ReadOnlyStatusCategoryRepository>();

        //Services
        x.For<IEvidenceTypeService>().Use<EvidenceTypeService>();
        x.For<IStatusCategoryService>().Use<StatusCategoryService>();
    }
}

然后注册如下:

IContainer yourContainer = new Container();
yourContainer.Configure(c =>
{
    c.IncludeRegistry<WebsiteRegistry>();
});