将存储过程与服务类一起用于存储库模式

时间:2018-06-29 23:14:22

标签: c# asp.net-mvc entity-framework-6

背景

在Web应用程序中,我创建存储过程,然后创建edmx文件以使用存储过程来处理所有数据库交互。

但是我开始怀疑我是否做对了,因为,如您在下面的示例中所见,

  1. 即使在被调用方法不需要数据库工作的情况下,每次Context被调用时,我都实例化Controller的两个实例

  2. 我要在每个存储库中实例化一个Context的实例,因此当一个请求需要从存储库A和B中获取数据时,我有两个Context的实例。

存储库A

public class RepositoryA
{
            private readonly Context _context;

            public RepositoryA()
            {
                _context = new Context();
            }

            public List<CLASS> GetA(int id)
            {
                return _context.GetByID(id);
            }
}

存储库B

public class RepositoryB
{
            private readonly Context _context;

            public RepositoryB()
            {
                _context = new Context();
            }

            public List<CLASS> GetB(int id)
            {
                return _context.GetByID(id);
            }
}

控制器

public class Controller
{
            private readonly IRepositoryA _reposA;
            private readonly IRepositoryB _reposB;

            public Controller() : this(new RepositoryA(), new RepositoryB())
            {}

            public Controller(IRepositoryA a, IRepositoryB b)
            {
                _respoA = a;
                _reposB = b;
            }

            public ActionResult METHOD()
            {
                //do something with both RepositoryA and RepositoryB 
                var dataFromA = _reposA.GetA(ID); 
                var dataFromB = _reposB.GetB(ID);

                return View(someData);
            }
}

现在的问题是:我不确定这是否应该是正常的实现,因此我一直在尝试找出如何以更有效和可测试的方式进行设置,并且尝试了类似的方法这个。

我相信这种设计解决了我的一些担忧:

  1. 每次调用Controller时都会调用服务,但是不会每次都实例化Context(每个请求都实例化Context)。

  2. 当服务同时需要存储库A和存储库B时,它将使用相同的上下文

但是,在Service的设置方式下,我无法使用测试数据对Service进行单元测试,因为无法使用模拟存储库。

public class Controller
{
        private Service _service;

        public Controller()
        {
            _service =  new Service();
        }

        public ActionResult METHOD()
        {
            _service.DoSomethingWithRepoAandB(); 

            return View();
        }
}

public class Service
{
            public void DoSomethingWithRepoAandB()
            {
                 using (var _context = new Context())
                 {
                     RepositoryA a = new RepositoryA(_context);
                     RepositoryB b = new RepositoryB(_context);
                     something = a.DoSomethingWithA();
                     otherThing = b.DoOtherThingWithB();
                 }                    
            }
}

所以,我认为我应该像这样设置Service

通过这种设计,每次调用Context时都会实例化Controller(除非我在Service方法中实例化Controller),但是我可以通过传递来进行单元测试模拟存储库。

public class Service
{
    private readonly Context _context;
    private IRepositoryA _a;
    private IRepositoryB _b;

    public Service()
    {
         _context = new Context();
         _a = new RepositoryA(_context);
         _b = new RepositoryB(_context);
    }        

    // Pass Mock Repositories in unit tests
    public Service(RepositoryA a, RepositoryB b)
    {
        _a = a;
        _b = b;
    }

    public void DoSomethingWithRepoAandB()
    {
        something = _a.DoSomethingWithA();
        otherThing =_b.DoOtherThingWithB();  
    }
}

我这样做是完全错误还是在正确的轨道上?我将不胜感激。

1 个答案:

答案 0 :(得分:-1)

您的服务不应包含有关您的上下文的任何信息,这些信息只能由存储库遵循SOLID原则访问。

您的图层访问应如下:

控制器->服务->存储库->上下文

在IRepository接口上,您将拥有要调用的方法,并且可以手动实例化它们,但是要正确实现,必须设置依赖项注入。

此外,您的存储库构造函数不会接收任何上下文作为参数,因此您无法执行以下操作:

RepositoryA a = new RepositoryA(_context);

另一方面,您的控制器也不应访问存储库,因为它会破坏您的体系结构

public ActionResult METHOD()
    {
        //do something with both RepositoryA and RepositoryB 
        var dataFromA = _reposA.GetA(ID);
        var dataFromB = _reposB.GetB(ID);

        return View(someData);
    }

这是正确的代码,需要进一步了解:

public class RepositoryA : IRepositoryA
{
    private readonly Context _context;

    public RepositoryA(Context context)
    {
        _context = context;
    }

    public List<CLASS> GetA(int id)
    {
        return _context.GetByID(id);
    }
}

public interface IRepositoryA
{
    List<CLASS> GetA(int id);
}

public class RepositoryB : IRepositoryB
{
    private readonly Context _context;

    public RepositoryB(Context context)
    {
        _context = context;
    }

    public List<CLASS> GetB(int id)
    {
        return _context.GetByID(id);
    }
}

public interface IRepositoryB
{
    List<CLASS> GetB(int id);
}

public class Controller
{
    private IService _service;

    public Controller(IService service)
    {
        _service = service;
    }

    public ActionResult METHOD(int id)
    {
        //do something with both RepositoryA and RepositoryB THROUGH the service. The service needs to hold the business rules, and repositories should only care about querying data and handling contexts.
        var data = _service.DoSomethingWithRepoAandB(id)

        return View(data);
    }

}

public class Service : IService
{
    private IRepositoryA _a;
    private IRepositoryB _b;

    // Pass Mock Repositories in unit tests -> PS: You can't have 2 constructors if you're using dependency injection.
    public Service(RepositoryA a, RepositoryB b)
    {
        _a = a;
        _b = b;
    }

    public void DoSomethingWithRepoAandB(int id)
    {
        var something = _a.GetA(id);
        var otherThing = _b.GetB(id);
    }
}

public interface IService
{
    void DoSomethingWithRepoAandB(int id);
}

public class Bootstrapper
{
    //this class should be in a separated assembly, responsible for handling the dependency injection. Using Simple Injection syntax just as an example

    public static void RegisterServices(Container container) //IoC Container
    {
        container.Register<IService, Service>(Lifestyle.Scoped);
        container.Register<IRepositoryA, RepositoryA>(Lifestyle.Scoped);
        container.Register<IRepositoryB, RepositoryB>(Lifestyle.Scoped);
        container.Register<Context>(() => {
            var options = // Configure your ContextOptions here
            return new Context(options);
        });
    }
}

public class Startup
{
    //This is your startup configuration if you're using WebApi. If you're on MVC, you can do this on your Global.asax
    public void Configuration()
    {
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); 
        BootStrapper.RegisterServices(container);
    }
}