我试图将依赖项注入到旧版ASP.NET .asmx Web服务中,但是我发现它们为null。这是我的代码:
Ninject绑定模块:
public class NinjectBindings : Ninject.Modules.NinjectModule
{
public override void Load()
{
Bind<IClientContextFactory>().To<ClientContextFactory>();
Bind<IMapper>().ToMethod(AutoMapper).InSingletonScope();
}
private IMapper AutoMapper(Ninject.Activation.IContext context)
{
Mapper.Initialize(config =>
{
config.ConstructServicesUsing(type => context.Kernel.Get(type));
// Users
config.CreateMap<User, UserDto>();
// Usergrid
config.CreateMap<UserDto, UserGridDetails>();
// Supervisor
config.CreateMap<User, SupervisorDto>();
// Branch
config.CreateMap<Branch, BranchDto>();
});
Mapper.AssertConfigurationIsValid(); // optional
return Mapper.Instance;
}
}
然后我在tGlobal.asax中创建一个内核实例:
protected override IKernel CreateKernel()
{
IKernel kernel = new StandardKernel(new NinjectBindings());
return kernel;
}
在我的Web服务(.asmx)中:
[Inject]
public IClientContextFactory contextFactory { get; set; }
[Inject]
public IMapper mapper { get; set; }
public GridService()
{
contextFactory = DependencyResolver.Current.GetService<IClientContextFactory>();
mapper = DependencyResolver.Current.GetService<IMapper>();
}
稍后,我尝试使用依存关系,如下所示:
List<UserGridDetails> userList = new User(contextFactory, mapper).GetUsers();
在这里,我发现contextFactory和mapper实例均为null。我调试了该应用程序,并确保执行了所有上述代码。我在做什么错了?
答案 0 :(得分:0)
使用此处建议的解决方案解决了它: Ninject inject a service interface in a web service
您需要从WebServiceBase
中的Ninject.Web.WebServiceBase
扩展Web服务类