以下是一个使用ASP.NET MVC 5和依赖注入的解决方案示例:
namespace YourProject.Services
{
public class UserService : IUserService
{
public string GetUserName()
{
return "John Doe";
}
}
}
namespace YourProject.Services
{
public interface IUserService
{
string GetUserName();
}
}
using System.Web.Mvc;
using YourProject.Services;
namespace YourProject.Controllers
{
public class HomeController : Controller
{
private readonly IUserService _userService;
public HomeController(IUserService userService)
{
_userService = userService;
}
public ActionResult Index()
{
string userName = _userService.GetUserName();
return Content("Hello, " + userName);
}
}
}
using System.Web.Mvc;
using System.Web.Routing;
using Unity;
using Unity.Mvc5;
using YourProject.Services;
namespace YourProject
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
var container = new UnityContainer();
container.RegisterType();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
}
在这个示例中,我们创建了一个名为“UserService”的服务类和相应的接口“IUserService”。然后,我们在“HomeController”类的构造函数中注入了“IUserService”接口的实例。最后,在“Global.asax.cs”文件中的“Application_Start”方法中使用Unity容器注册了依赖关系并设置了依赖解析器。
使用这种方法,我们可以通过依赖注入来解耦控制器和服务类,使代码更易于测试和维护。