StructureMap ASP.net MVC不注入接口

时间:2014-04-12 16:52:22

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

我试图让结构映射依赖项正常工作,但是在构造函数中放置接口而不是放置类名时,它无法正常工作。

以下代码有效:

public class HomeController : Controller
{
    private readonly MyService _service;

    public HomeController(MyService service)
    {
        _service = service;
    }

    public ActionResult Index()
    {
        return View();
    }
}

public class MyService : IService
{
    public string GetName()
    {
        return "Hello";
    }
}

public interface IService
{
    string GetName();
}

但以下代码不起作用:

public class HomeController : Controller
{
    private readonly IService _service;

    public HomeController(IService service)
    {
        _service = service;
    }

    public ActionResult Index()
    {
        return View();
    }
}

public class MyService : IService
{
    public string GetName()
    {
        return "Hello";
    }
}

public interface IService
{
    string GetName();
}

以下是DependencyResolution类的逻辑:

  public static IContainer Initialize() {
        ObjectFactory.Initialize(x =>
                    {
                        x.Scan(scan =>
                                {
                                    scan.TheCallingAssembly();
                                    scan.WithDefaultConventions();
                                });
        //                x.For<IExample>().Use<Example>();
                    });
        return ObjectFactory.Container;
    }

我正在使用StructureMap.MVC4 nuget包来设置依赖注入。我做错了什么?

2 个答案:

答案 0 :(得分:2)

在你的调用程序集中,如果你只有一个表示接口的实现类,你可以使用如下所示

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

没有SingleImplementationsOfInterface()方法,structuremap无法识别IService接口的正确实现类。

你可以像下面这样映射

ObjectFactory.Initialize(x =>
        {
            x.Scan(scan =>
            {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
            });
            x.For<IService>().Use<MyService>();
        });

答案 1 :(得分:1)

尝试这段代码:

 public class MvcBootStrapper
        {
            public static void ConfigurationStructureMap()
            {
                ObjectFactory.Initialize(x =>
                {
                    x.AddRegistry<MyService>();
                });
            }
        }

最后注册你的类和接口:

 public class SampleRegistery : Registry
        {
            public SampleRegistery ()
            {
                ForRequestedType<IService>().TheDefaultIsConcreteType<MyService>();
            }
        }

有关详细信息,请参阅this文章。