“无法解析IProjectServices”与MVC中的服务层接口

时间:2013-02-19 02:41:39

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我不确定我是否正确行事。我有一个名为Project.Services的项目,它包含我的MVC应用程序中的控制器所利用的一堆服务。

在将服务项目暴露给Web项目方面 - 我在我的Web项目中定义了一个名为“IProjectServices”的接口,其中包含一些与我需要的对应的空白方法。

然后,我尝试使用

之类的语法在Services Project中实现此接口
public class ProjectServices : IProjectServices

我现在收到“无法解决IProjectServices”错误 - 在开始深入研究之前,我是否正确使用了接口?

我认为网络项目正在说“嘿,我需要某种服务,但我不想直接依赖服务项目,所以我将创建一个界面”,然后服务项目说“嘿没问题我会实现它,但也许另一个项目(如测试)将来会以不同的方式实现它,所以我们没有紧密耦合“。我在想吗?

1 个答案:

答案 0 :(得分:2)

以下是使用Unity的示例实现。我希望这会有所帮助。

从控制器向后工作......

MVC项目:DashboardController.cs

public class DashboardController : Controller
{
    private readonly IDashboardService dashboardService;

    public DashboardController(IDashboardService dashboardService)
    {
        this.dashboardService = dashboardService;
    }

    [HttpGet]
    public ActionResult Index()
    {
        var model = this.dashboardService.BuildIndexViewModel();

        return this.View(model);
    }
}

MVC项目:Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // Standard MVC setup
        // ...

        // Application configuration 
        var container = new UnityContainer();
        new AppName.Services.UnityBootstrap().Configure(container);
    }
}

服务项目:DashboardService.cs

public class DashboardService : IDashboardService
{
    // ctor
    // ...

    public IndexViewModel BuildIndexViewModel()
    {
        var currentPerformanceYear = this.repository.GetMaxPerformanceYear().PerformanceYearID;
        var staff = this.repository.GetStaffBySamAccountName(this.currentUser.Identity.Name);

        var model = new IndexViewModel
        {
            StaffName = staff.FullName,
            StaffImageUrl = staff.StaffImageUrl,
            // ...
        };

        return model;
    }
}

服务项目:IDashboardService.cs

public interface IDashboardService
{
    IndexViewModel BuildIndexViewModel();
}

服务项目:UnityBootstrap.cs

public class UnityBootstrap : IUnityBootstrap
{
    public IUnityContainer Configure(IUnityContainer container)
    {
        return container.RegisterType<IDashboardService, DashboardService>()
                        .RegisterType<ISharePointService, SharePointService>()
                        .RegisterType<IStaffService, StaffService>();
    }
}

公司企业库实用程序项目:IUnityBootstrap.cs

public interface IUnityBootstrap
{
    IUnityContainer Configure(IUnityContainer container);
}