这里我想添加单元依赖性soi将3个项目作为Univers(MVC),Moon(ClassLib),服务(ClassLib)负责单元依赖
月球 在这里我采用了1-Interface 2-ClassFile
public interface IMoon
{
string Gotomoon();
}
public class MoonImp : IMoon
{
public string Gotomoon()
{
return"Hello moon how r u.....";
}
}
Service.cs
这里我采取了1-IService 2-Service 3-ContainerBootstrap.cs
public interface IService
{
string Gotomoon();
}
public class ServiceImp : IService
{
private IMoon Moon;
public ServiceImp(IMoon moons)
{
this.Moon = moons;
}
public string Gotomoon()
{
return Moon.Gotomoon();
}
ContainerBootstrap.cs
public static void RegisterTypes(IUnityContainer container)
{
container
.RegisterType<IMoon, MoonImp>()
.RegisterType<IService, ServiceImp>();
}
现在我来到Universe它是我的MVC文件 在这里我拿了UnityDependencyResolver .cs文件并写了一些代码
public class UnityDependencyResolver : IDependencyResolver
{
private readonly IUnityContainer container;
public UnityDependencyResolver(IUnityContainer container)
{
this.container = container;
}
public object GetService(Type serviceType)
{
if (!this.container.IsRegistered(serviceType))
{
return null;
}
else
{
return this.container.Resolve(serviceType);
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (!this.container.IsRegistered(serviceType))
{
return new List<object>();
}
else
return this.container.ResolveAll(serviceType);
}
**UnityConfig.cs**
现在我在App_Start
中将类文件作为UnityConfig.cspublic class UnityConfig
{
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(()=>
{
IUnityContainer container = new UnityContainer();
RegisterType(container);
return container;
});
public static IUnityContainer Getconfiguration()
{
return container.Value;
}
public static void RegisterType(IUnityContainer container)
{
ContainerBootstrap.RegisterTypes(container);
}
}
Global.asax中 现在我将该文件注册为全球
DependencyResolver.SetResolver(new UnityDependencyResolver(UnityConfig.Getconfiguration()));
现在我在HomeController.cs中实现
private IService serviced;
public HomeController(IService service)
{
this.serviced = service;
}
public ActionResult Index()
{
ViewBag.msg = serviced.Gotomoon();
return View();
}
答案 0 :(得分:0)
我已经遇到了这个问题而且我还和Mr.j一起...评论....这里你没有注册你的HomeCntroller 请添加此
public static void RegisterType(IUnityContainer container)
{
ContainerBootstrap.RegisterTypes(container);
container.RegisterType<HomeController>();
}