interface and cannot be constructed on Unity config

后端 未结 1 989
醉梦人生
醉梦人生 2021-01-29 13:39

I have trouble to use Unity on this project.

The error is

The current type, Business.Interfaces.IPersonnelBusiness, is an interface and cannot b

相关标签:
1条回答
  • 2021-01-29 14:12

    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
    
        ...
    
    0 讨论(0)
提交回复
热议问题