2016-03-12 86 views
0

我正尝试在C#Web API中创建一个休息服务。C#Web API中的依赖注入

目前我没有考虑任何DB决策,因此我添加了一个模拟类库。

我正在创建一个模型接口并在模拟类库中实现模型。

public interface IUser 
{ 
    int userId { get; set; } 
    string firstName { get; set; } 
    string lastName { get; set; } 
    string email { get; set; } 

    List<IUser> getAllUsers(); 
    IUser getUser(int ID); 
    bool updateUser(IUser user); 
    bool deleteUser(int ID); 
} 

,并在模拟类库

public class User : IUser 
{ 
    public string email { get; set; } 
    public string firstName { get; set; } 
    public string lastName { get; set; } 
    public int userId { get; set; } 

    public bool deleteUser(int ID) 
    { 
     throw new NotImplementedException(); 
    } 

    public List<IUser> getAllUsers() 
    { 
     throw new NotImplementedException(); 
    } 

    public IUser getUser(int ID) 
    { 
     throw new NotImplementedException(); 
    } 

    public bool updateUser(IUser user) 
    { 
     throw new NotImplementedException(); 
    } 
} 

实现这个现在模拟库引用的服务应用程序实现的接口。

现在我需要从服务应用程序中的控制器类调用模拟实现。

如何在不创建循环依赖的情况下执行此操作。我做了一些研究,并提出了一个解决方案,即DI是要走的路。

有人可以帮我实现这与代码示例?

非常感谢。

+0

参见http://stackoverflow.com/q/12977743/126014 –

回答

0

如果您不介意可能使用哪个IoC容器,我会推荐Ninject。

你需要通过的NuGet安装下一个软件包:

然后在RegisterServices的端部的Ninject配置文件NinjectWebCommon.cs()方法中添加以下代码:

kernel.Bind<IUser>().To<User>(); 

而现在只需添加IUSER作为参数到控制器类和Ninject将自动注入它。

public class MyController : Controller 
{ 

private IUser _user; 

    // Ninject will automatically inject a User instance here 
    // on controller creation 
    public MyController(IUser user) 
    { 
     _user = user; 
    } 
} 

有不同的方法使用Ninject,因此您可以搜索其他更适合您的需求的方法。

0

“现在我需要从服务应用程序中的控制器类调用模拟实现。”

这听起来不对。我认为你在这里有一个设计问题;为什么你需要从你的服务应用程序中参考模拟IUser的实现?

  • 有一点要记住的是,的客户拥有的接口,所以IUser界面不会在模拟类库都属于;理想情况下应该在一个完全独立的程序集中定义,以便您的服务类库可以引用它(并在需要时为其提供它们自己的实现),以便您的模拟类库

  • 这是Dependency Inversion Principle,虽然我同意某种类型的DI库可以帮助您管理这种控制反转的实现,但我认为它从长远来看不会对您有所帮助。您可能仍会遇到容器本身中的相同循环引用问题。

  • 现在我觉得你首先需要看一下使用Stairway Pattern,让您的依赖关系正确倒你看看使用任何DI库

0

现在模拟库引用服务应用程序之前实现界面。

这是问题的根源。我建议将您的数据访问层的接口移出到一个单独的项目中。然后,您可以使用模拟/内存实现创建项目,然后使用真实实现添加另一个项目。

另一件事是您的IUser是您的DTO(数据传输对象)的契约,但它包含DAO(数据访问对象)方法。通常情况下,您想要将这些问题与存储库模式分开。

public interface IUserRepository 
{ 
    IEnumerable<IUser> GetAllUsers(); 
    IUser GetUser(int id); 
    ... 
} 

此存储库是您将注入到您的API控制器。