依赖注入 - Unity构造函数注入不起作用,只有getter setter注入

时间:2017-03-07 07:33:06

标签: asp.net-mvc service dependency-injection repository unity-container

我遇到Unity依赖注入问题。当我尝试使用构造函数注入时,我注入的服务保持为空/ null。

public UserService(IUnitOfWorkIntranet unitOfWork, IUserRepository userRepository)
   {
     mappingToDomainModel = IntranetMappingToDomainModel.GetMappingToDomainModelInstance;
     IntranetAutoMapperConfiguration autoMapper = IntranetAutoMapperConfiguration.GetAutoMapperConfigurationInstance;
     unitOfWorkIntranet = unitOfWork;
     userRepository = userRepository;
    } 

但是,当我使用getter时,一切正常。

private IUserRepository _userRepository
   {
      get
   {
      return GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserRepository)) as UserRepository;
   }
   } 

据我所知,它在UnityConfig.cs中正确配置

container.RegisterType<IUnitOfWorkIntranet, UnitOfWorkIntranet>();
container.RegisterType<IUserService, UserService>();
container.RegisterType<IUserRepository, UserRepository>();

我在这里遗漏了什么吗?为什么我的构造函数注入了?

欢迎任何帮助,问候!

1 个答案:

答案 0 :(得分:0)

使用Unity的构造函数注入有一个简单的工作示例:

public interface IUnitOfWorkIntranet { }

public class UnitOfWorkIntranet : IUnitOfWorkIntranet{}

public interface IUserRepository { }

public class UserRepository : IUserRepository{}

public interface IUserService{}

public class UserService : IUserService
{
    public IUnitOfWorkIntranet UnitOfWork { get; }
    public IUserRepository UserRepository { get; }
    public UserService(IUnitOfWorkIntranet unitOfWork, IUserRepository userRepository)
    {
        UnitOfWork = unitOfWork;
        UserRepository = userRepository;
    }
}

配置和解决:

var container = new UnityContainer();
container.RegisterType<IUnitOfWorkIntranet, UnitOfWorkIntranet>();
container.RegisterType<IUserService, UserService>();
container.RegisterType<IUserRepository, UserRepository>();

var service = (UserService)container.Resolve<IUserService>();