interface and cannot be constructed on Unity config

余生颓废 提交于 2019-12-02 13:27:18

As pointed out in the comments, the issue is that you are instantiating 2 different containers, once in your initializer:

    private static Lazy<IUnityContainer> container =
      new Lazy<IUnityContainer>(() =>
      {
          var container = new UnityContainer(); // <-- new container here
          RegisterTypes(container);
          return container;
      });

And once in your RegisterTypes method:

    public static void RegisterTypes(IUnityContainer container)
    {
        // NOTE: To load from web.config uncomment the line below.
        // Make sure to add a Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // TODO: Register your type's mappings here.
        // container.RegisterType<IProductRepository, ProductRepository>();
        container = new UnityContainer(); // <-- new container here

    ...

The type mappings are added in the RegisterTypes method to a different instance than the container you are passing in as an argument.

To make it work right, you should remove the instantiation of the container in RegisterTypes so it can use the instance that is passed in the parameter.

    public static void RegisterTypes(IUnityContainer container)
    {
        // NOTE: To load from web.config uncomment the line below.
        // Make sure to add a Unity.Configuration to the using statements.
        // container.LoadConfiguration();

        // TODO: Register your type's mappings here.
        // container.RegisterType<IProductRepository, ProductRepository>();
        // container = new UnityContainer(); // <-- Remove this

    ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!