在這裏,我瓦納添加單元相關SOI已經採取3項目爲UNIVERS(MVC),月亮(CLASSLIB),服務(CLASSLIB)及其負責單位Dependecy沒有爲此對象定義的無參數構造函數。當我嘗試團結依賴
月亮 在這裏,我有取1-接口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-服務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>();
}
現在我來宇宙的我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**
現在我已經採取了類文件作爲Unity_Config.cs in App_Start
public 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();
}
爲什麼減去在這裏,我想趁自己錯誤的無參數化的發現 –
錯誤是告訴你什麼問題..聽起來像你缺少一個空的構造函數在你的一個類.. – MethodMan
但我認爲每一件事情都很好,如果你做錯了任何錯誤,你可以plz建議我在哪裏做什麼錯誤... –