问题:
运行时,显示 未将对象引用设置到对象的实例。
获取接口实现方法 失败了
请问:少了哪一步,或者哪一句代码,,,导致对象注册失败了。
(1)初始化代码
public class Bootstrapper { public static IUnityContainer Init() { string containerName = ConfigurationManager.AppSettings["containerName"].ToString(); var container = BuildUnityContainer(containerName); // DependencyResolver.SetResolver(new UnityDependencyResolver(container)); return container; } private static IUnityContainer BuildUnityContainer(string containerName) { var container = new UnityContainer(); UnityConfigurationSection configuration = (UnityConfigurationSection)ConfigurationManager.GetSection(UnityConfigurationSection.SectionName); if (String.IsNullOrEmpty(containerName)) { containerName = "defaultContainer"; } configuration.Configure(container, containerName); return container; } }
(2)
public class UnityDependencyResolver : IDependencyResolver { IUnityContainer container; public UnityDependencyResolver(IUnityContainer container) { this.container = container; } public object GetService(Type serviceType) { if (!this.container.IsRegistered(serviceType)) { return null; } return container.Resolve(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { return container.ResolveAll(serviceType); } }
(3)
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
Bootstrapper.Init();
}
(4)
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity>
<container name="containerName">
<register type="KJFW.IDAL.IAdminDAL,KJFW" mapTo="KJFW.DAL.AdminDAL,KJFW"></register>
</container>
</unity>
(5)控制器里面
[Dependency]
IAdminDAL IadminDal{get;set;}
public ActionResult ManagerIndex()
{
List<AdminModelExtend> list = IadminDal.login("admin", "E10ADC3949BA59ABBE56E057F20F883E");
return Content(list.Count.ToString());
}
定义一个Unity工厂类public class UnityControllerFactory : DefaultControllerFactory;
然后在init()方法中注册一下:container.RegisterType<IControllerFactory, UnityControllerFactory>();
就可以实现依赖注入了
配置项注册了么?反编译下dll看下生成的程序集
已经解决了,谢谢
@弦断有谁听: 什么引起的呢?楼主解决了说下原因嘛,或许以后其他人看到也就直接能够反应过来了!O(∩_∩)O~
@弦断有谁听: 刚在上面看到。。