如何在asp.net-mvc中使用Structuremap自动注册?

时间:2015-01-28 10:37:07

标签: c# asp.net-mvc structuremap structuremap3

我有一个简单的mvc应用程序,它有3层

  1. Ui =>尊重Common And Services
  2. 通用
  3. 服务=>对Common
  4. 有所了解

    我在公共图层中定义我的服务合同,并在服务层

    中实现它
    //Common layer
    public interface IPersonService
    {
      void Foo();
    }
    //Services layer
    public classPersonService:IPersonService
    {
      void Foo()
      {
        //To DO
      }
    }
    

    在我的Global.asax中,我为初始的Structuremap容器编写了这段代码

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

    现在,在我的控制器中,当我想从IPersonService获取实例时,就像这样

    var personService= ObjectFactory.GetInstance<IPersonService>();
    

    我收到此错误

      

    没有注册默认实例,无法自动确定类型'* .IPersonService'

    有什么想法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您可以使用AssembliesFromApplicationBaseDirectory()函数指定要扫描的其他程序集,如下所示:

scan.AssembliesFromApplicationBaseDirectory(a => a.FullName.StartsWith("YourNamespace.Common"));
scan.AssembliesFromApplicationBaseDirectory(a => a.FullName.StartsWith("YourNamespace.Services"));

当您将此问题标记为StructureMap 3问题时,我建议不要使用ObjectFactory,因为Jeremy Miller(StructureMap的作者)明确表示will be removed in future version。实际上,您应该收到警告,告知它将在以后的版本中删除。

相反,您应该像以下那样配置容器:

IContainer container = new Container();
container.Configure(c => {
    c.IncludeRegistry<YourRegistry>();
});

DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));

您可以阅读有关StructureMap的注册管理机构here的更多信息。