Inject same DataContext instance across several types with Unity

前端 未结 4 1344
旧巷少年郎
旧巷少年郎 2020-12-28 11:01

Suppose I have IRepository interface and its implementation SqlRepository that takes as an argument LINQ to SQL DataContext. Suppose as well that I have IService interface a

4条回答
  •  情书的邮戳
    2020-12-28 11:30

    If I understand your question correctly (and if you are using unity...I suppose you do because you have taggged it with unity) you could do something like this:

    In your repository implementions,

    [InjectionConstructor]
    public SqlRepository(
        [Dependency] DataContext ctx)
    

    but then you have to mark the service contructor in the same manner and use the container to resolve your services as well as the repository. The DataContext also has to be in the container to make it work.

    An alternative approach is to do something like this with your repository:

    [InjectionMethod]
    public void Initialize(
        [Dependency] DataContext ctx
    

    this will tell unity to call this method if you will, in your service constructor, use unity with the BuildUp method...something like this:

    unitycontainer.BuildUp(repository);
    

    I guess that´s not quite what your looking for but please tell me if I´m on the right track and I´ll see if I can help you further...

    Cheers / J

提交回复
热议问题