How do I use Dependency Injection with Unit of Work and Repositories in C#? (Not a web based App)Ninject - In what scope DbContext should get binded when RequestScope is meaningless?Ninject Scope issue with Tasks/ThreadsUnit Of Work Pattern and Unity and Generic Repository ImplementationUnit of Work with Dependency InjectionNinject not disposing objects mapped as InRequestScope if they reference objects mapped as InSingletonScopeUnit of Work + Repository Pattern: The Fall of the Business Transaction ConceptUnit of Work, Repository, Injection, using blockEF6, Unit of Work and Repository Pattern - Is this the wrong pattern for a sync service?Purpose of registering repositories in this UnitOfWork implementationDisposing of context in the Unit Of Work / Repository patternUnitOfWork exposed in service layer. Am i approaching this correctly?

Why are we moving in circles with a tandem kayak?

Were there any unmanned expeditions to the moon that returned to Earth prior to Apollo?

What kind of horizontal stabilizer does a Boeing 737 have?

Planting Trees in Outer Space

Was Donald Trump at ground zero helping out on 9-11?

How can I convert a linear narrative into a branching narrative?

How should I save/invest for my son

How to innovate in OR

Patio gate not at right angle to the house

In the Schrödinger equation, can I have a Hamiltonian without a kinetic term?

My employer is refusing to give me the pay that was advertised after an internal job move

Why does the Rust compiler not optimize code assuming that two mutable references cannot alias?

How does Asimov's second law deal with contradictory orders from different people?

Can you remove a blindfold using the Telekinesis spell?

Easy way to get process information from a window

Help me, I hate squares!

How can a class have multiple methods without breaking the single responsibility principle

Can I shorten this filter, that finds disk sizes over 100G?

How to prevent a single-element caster from being useless against immune foes?

Russian pronunciation of /etc (a directory)

PCB design using code instead of clicking a mouse?

Applying for mortgage when living together but only one will be on the mortgage

Best practice for keeping temperature constant during film development at home

What parameters are to be considered when choosing a MOSFET?



How do I use Dependency Injection with Unit of Work and Repositories in C#? (Not a web based App)


Ninject - In what scope DbContext should get binded when RequestScope is meaningless?Ninject Scope issue with Tasks/ThreadsUnit Of Work Pattern and Unity and Generic Repository ImplementationUnit of Work with Dependency InjectionNinject not disposing objects mapped as InRequestScope if they reference objects mapped as InSingletonScopeUnit of Work + Repository Pattern: The Fall of the Business Transaction ConceptUnit of Work, Repository, Injection, using blockEF6, Unit of Work and Repository Pattern - Is this the wrong pattern for a sync service?Purpose of registering repositories in this UnitOfWork implementationDisposing of context in the Unit Of Work / Repository patternUnitOfWork exposed in service layer. Am i approaching this correctly?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I see a lot of questions and answers on this topic, however the vast majority are dealing with ASP.Net or other web based applications and something called .InRequestScope. I have yet to find this method in Ninject with a Windows Application.



I have the usual Unit of Work (UoW) and Repository (Repo) classes and Interfaces, but I am wanting to inject the same DbContext into both, each time a UoW is run from the DIContainer. My code looks like this;



public class UnitOfWork : IUnitOfWork, IDisposable

private readonly FinancialContext _context;

private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get return _accountRepository;


UnitOfWork(IMyContext context, IAccountRepository accountRepository)

_context = context;
_accountRepository = accountRepository;


public void SaveChanges()

_context.SaveChanges();


public void Dispose()

_context.Dispose();



public class AccountRepository : Repository<Account>, IAccountRepository

public AccountRepository(IMyContext context) : base(context)



The DIContainer holds the following associations;



Bind<IUnitOfWork>().To<UnitOfWork>().InTransientScope();
Bind<IUnitOfWorkFactory>().ToFactory();

Bind<IMyContext>().To<MyContext>().InSingletonScope();

Bind<IAccountTypeRepository>().To<AccountTypeRepository>().InTransientScope();


I'll come back to the .InSingletonScope();



The way I have seen people do this normally has been in the UoW Properties for each Repo to have code to this effect;



private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get

if(_accountRepository = null)

_accountRepository = new AccountRepository(_context);

return _accountRepository;




And remove the injected repositories from the Constructor, there by ensuring that each instance of a repository using the same _context.



However in my mind this breaks the Dependency Injection for this class. Is there a way to do this where each creation of a UoW like so;



public TestUnitOfWork(IUnitOfWorkFactory unitOfWork)

using (var UoW = unitOfWork.Create())

Work done on UoW...




Currently the .InSingletonScope allows this, but is this keeping an instance of the context always open? Introducing the errors associated with not disposing a context properly?



Or is it better to create a Factory for the Repositories and give them a context parameter, then in the properties initialise it like so;



private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get

if(_accountRepository = null)

_accountRepository = RepositoryFactory.CreateAccountRepository(_context);

return _accountRepository;




Thanks in advance for any help!










share|improve this question
























  • This one can be helpful for you:stackoverflow.com/questions/23081707/…

    – Jan Muncinsky
    Jun 22 '18 at 10:39











  • I am just wrestling with the exact same dilemma. Have you come across a viable solution to this yet or have you taken the RepositoryFactory route? I'll keep searching...

    – Michael Kargl
    Jul 20 '18 at 17:11











  • Hi Michael, I went with the Factory approach in the end, Ninject's Extensions.Factory uses DI to resolve it's dependencies, so if you are using Factory.Create() for an object, it resolves that objects dependencies too, so I believe this is still very testable and clean!

    – Tristan Trainer
    Jul 25 '18 at 9:30

















2















I see a lot of questions and answers on this topic, however the vast majority are dealing with ASP.Net or other web based applications and something called .InRequestScope. I have yet to find this method in Ninject with a Windows Application.



I have the usual Unit of Work (UoW) and Repository (Repo) classes and Interfaces, but I am wanting to inject the same DbContext into both, each time a UoW is run from the DIContainer. My code looks like this;



public class UnitOfWork : IUnitOfWork, IDisposable

private readonly FinancialContext _context;

private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get return _accountRepository;


UnitOfWork(IMyContext context, IAccountRepository accountRepository)

_context = context;
_accountRepository = accountRepository;


public void SaveChanges()

_context.SaveChanges();


public void Dispose()

_context.Dispose();



public class AccountRepository : Repository<Account>, IAccountRepository

public AccountRepository(IMyContext context) : base(context)



The DIContainer holds the following associations;



Bind<IUnitOfWork>().To<UnitOfWork>().InTransientScope();
Bind<IUnitOfWorkFactory>().ToFactory();

Bind<IMyContext>().To<MyContext>().InSingletonScope();

Bind<IAccountTypeRepository>().To<AccountTypeRepository>().InTransientScope();


I'll come back to the .InSingletonScope();



The way I have seen people do this normally has been in the UoW Properties for each Repo to have code to this effect;



private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get

if(_accountRepository = null)

_accountRepository = new AccountRepository(_context);

return _accountRepository;




And remove the injected repositories from the Constructor, there by ensuring that each instance of a repository using the same _context.



However in my mind this breaks the Dependency Injection for this class. Is there a way to do this where each creation of a UoW like so;



public TestUnitOfWork(IUnitOfWorkFactory unitOfWork)

using (var UoW = unitOfWork.Create())

Work done on UoW...




Currently the .InSingletonScope allows this, but is this keeping an instance of the context always open? Introducing the errors associated with not disposing a context properly?



Or is it better to create a Factory for the Repositories and give them a context parameter, then in the properties initialise it like so;



private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get

if(_accountRepository = null)

_accountRepository = RepositoryFactory.CreateAccountRepository(_context);

return _accountRepository;




Thanks in advance for any help!










share|improve this question
























  • This one can be helpful for you:stackoverflow.com/questions/23081707/…

    – Jan Muncinsky
    Jun 22 '18 at 10:39











  • I am just wrestling with the exact same dilemma. Have you come across a viable solution to this yet or have you taken the RepositoryFactory route? I'll keep searching...

    – Michael Kargl
    Jul 20 '18 at 17:11











  • Hi Michael, I went with the Factory approach in the end, Ninject's Extensions.Factory uses DI to resolve it's dependencies, so if you are using Factory.Create() for an object, it resolves that objects dependencies too, so I believe this is still very testable and clean!

    – Tristan Trainer
    Jul 25 '18 at 9:30













2












2








2


0






I see a lot of questions and answers on this topic, however the vast majority are dealing with ASP.Net or other web based applications and something called .InRequestScope. I have yet to find this method in Ninject with a Windows Application.



I have the usual Unit of Work (UoW) and Repository (Repo) classes and Interfaces, but I am wanting to inject the same DbContext into both, each time a UoW is run from the DIContainer. My code looks like this;



public class UnitOfWork : IUnitOfWork, IDisposable

private readonly FinancialContext _context;

private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get return _accountRepository;


UnitOfWork(IMyContext context, IAccountRepository accountRepository)

_context = context;
_accountRepository = accountRepository;


public void SaveChanges()

_context.SaveChanges();


public void Dispose()

_context.Dispose();



public class AccountRepository : Repository<Account>, IAccountRepository

public AccountRepository(IMyContext context) : base(context)



The DIContainer holds the following associations;



Bind<IUnitOfWork>().To<UnitOfWork>().InTransientScope();
Bind<IUnitOfWorkFactory>().ToFactory();

Bind<IMyContext>().To<MyContext>().InSingletonScope();

Bind<IAccountTypeRepository>().To<AccountTypeRepository>().InTransientScope();


I'll come back to the .InSingletonScope();



The way I have seen people do this normally has been in the UoW Properties for each Repo to have code to this effect;



private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get

if(_accountRepository = null)

_accountRepository = new AccountRepository(_context);

return _accountRepository;




And remove the injected repositories from the Constructor, there by ensuring that each instance of a repository using the same _context.



However in my mind this breaks the Dependency Injection for this class. Is there a way to do this where each creation of a UoW like so;



public TestUnitOfWork(IUnitOfWorkFactory unitOfWork)

using (var UoW = unitOfWork.Create())

Work done on UoW...




Currently the .InSingletonScope allows this, but is this keeping an instance of the context always open? Introducing the errors associated with not disposing a context properly?



Or is it better to create a Factory for the Repositories and give them a context parameter, then in the properties initialise it like so;



private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get

if(_accountRepository = null)

_accountRepository = RepositoryFactory.CreateAccountRepository(_context);

return _accountRepository;




Thanks in advance for any help!










share|improve this question














I see a lot of questions and answers on this topic, however the vast majority are dealing with ASP.Net or other web based applications and something called .InRequestScope. I have yet to find this method in Ninject with a Windows Application.



I have the usual Unit of Work (UoW) and Repository (Repo) classes and Interfaces, but I am wanting to inject the same DbContext into both, each time a UoW is run from the DIContainer. My code looks like this;



public class UnitOfWork : IUnitOfWork, IDisposable

private readonly FinancialContext _context;

private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get return _accountRepository;


UnitOfWork(IMyContext context, IAccountRepository accountRepository)

_context = context;
_accountRepository = accountRepository;


public void SaveChanges()

_context.SaveChanges();


public void Dispose()

_context.Dispose();



public class AccountRepository : Repository<Account>, IAccountRepository

public AccountRepository(IMyContext context) : base(context)



The DIContainer holds the following associations;



Bind<IUnitOfWork>().To<UnitOfWork>().InTransientScope();
Bind<IUnitOfWorkFactory>().ToFactory();

Bind<IMyContext>().To<MyContext>().InSingletonScope();

Bind<IAccountTypeRepository>().To<AccountTypeRepository>().InTransientScope();


I'll come back to the .InSingletonScope();



The way I have seen people do this normally has been in the UoW Properties for each Repo to have code to this effect;



private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get

if(_accountRepository = null)

_accountRepository = new AccountRepository(_context);

return _accountRepository;




And remove the injected repositories from the Constructor, there by ensuring that each instance of a repository using the same _context.



However in my mind this breaks the Dependency Injection for this class. Is there a way to do this where each creation of a UoW like so;



public TestUnitOfWork(IUnitOfWorkFactory unitOfWork)

using (var UoW = unitOfWork.Create())

Work done on UoW...




Currently the .InSingletonScope allows this, but is this keeping an instance of the context always open? Introducing the errors associated with not disposing a context properly?



Or is it better to create a Factory for the Repositories and give them a context parameter, then in the properties initialise it like so;



private IAccountRepository _accountRepository;
public IAccountRepository Accounts

get

if(_accountRepository = null)

_accountRepository = RepositoryFactory.CreateAccountRepository(_context);

return _accountRepository;




Thanks in advance for any help!







c# dependency-injection ninject repository-pattern unit-of-work






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 13 '18 at 19:06









Tristan TrainerTristan Trainer

4123 silver badges16 bronze badges




4123 silver badges16 bronze badges















  • This one can be helpful for you:stackoverflow.com/questions/23081707/…

    – Jan Muncinsky
    Jun 22 '18 at 10:39











  • I am just wrestling with the exact same dilemma. Have you come across a viable solution to this yet or have you taken the RepositoryFactory route? I'll keep searching...

    – Michael Kargl
    Jul 20 '18 at 17:11











  • Hi Michael, I went with the Factory approach in the end, Ninject's Extensions.Factory uses DI to resolve it's dependencies, so if you are using Factory.Create() for an object, it resolves that objects dependencies too, so I believe this is still very testable and clean!

    – Tristan Trainer
    Jul 25 '18 at 9:30

















  • This one can be helpful for you:stackoverflow.com/questions/23081707/…

    – Jan Muncinsky
    Jun 22 '18 at 10:39











  • I am just wrestling with the exact same dilemma. Have you come across a viable solution to this yet or have you taken the RepositoryFactory route? I'll keep searching...

    – Michael Kargl
    Jul 20 '18 at 17:11











  • Hi Michael, I went with the Factory approach in the end, Ninject's Extensions.Factory uses DI to resolve it's dependencies, so if you are using Factory.Create() for an object, it resolves that objects dependencies too, so I believe this is still very testable and clean!

    – Tristan Trainer
    Jul 25 '18 at 9:30
















This one can be helpful for you:stackoverflow.com/questions/23081707/…

– Jan Muncinsky
Jun 22 '18 at 10:39





This one can be helpful for you:stackoverflow.com/questions/23081707/…

– Jan Muncinsky
Jun 22 '18 at 10:39













I am just wrestling with the exact same dilemma. Have you come across a viable solution to this yet or have you taken the RepositoryFactory route? I'll keep searching...

– Michael Kargl
Jul 20 '18 at 17:11





I am just wrestling with the exact same dilemma. Have you come across a viable solution to this yet or have you taken the RepositoryFactory route? I'll keep searching...

– Michael Kargl
Jul 20 '18 at 17:11













Hi Michael, I went with the Factory approach in the end, Ninject's Extensions.Factory uses DI to resolve it's dependencies, so if you are using Factory.Create() for an object, it resolves that objects dependencies too, so I believe this is still very testable and clean!

– Tristan Trainer
Jul 25 '18 at 9:30





Hi Michael, I went with the Factory approach in the end, Ninject's Extensions.Factory uses DI to resolve it's dependencies, so if you are using Factory.Create() for an object, it resolves that objects dependencies too, so I believe this is still very testable and clean!

– Tristan Trainer
Jul 25 '18 at 9:30












1 Answer
1






active

oldest

votes


















0














The solution is the use Ninject's Extensions.Factory class and pass in an IAccountFactory.Create() to initialise a new object. This then uses the DI Container to resolve its dependencies and doesn't break the DI approach.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50844531%2fhow-do-i-use-dependency-injection-with-unit-of-work-and-repositories-in-c-not%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    The solution is the use Ninject's Extensions.Factory class and pass in an IAccountFactory.Create() to initialise a new object. This then uses the DI Container to resolve its dependencies and doesn't break the DI approach.






    share|improve this answer





























      0














      The solution is the use Ninject's Extensions.Factory class and pass in an IAccountFactory.Create() to initialise a new object. This then uses the DI Container to resolve its dependencies and doesn't break the DI approach.






      share|improve this answer



























        0












        0








        0







        The solution is the use Ninject's Extensions.Factory class and pass in an IAccountFactory.Create() to initialise a new object. This then uses the DI Container to resolve its dependencies and doesn't break the DI approach.






        share|improve this answer













        The solution is the use Ninject's Extensions.Factory class and pass in an IAccountFactory.Create() to initialise a new object. This then uses the DI Container to resolve its dependencies and doesn't break the DI approach.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 22:03









        Tristan TrainerTristan Trainer

        4123 silver badges16 bronze badges




        4123 silver badges16 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f50844531%2fhow-do-i-use-dependency-injection-with-unit-of-work-and-repositories-in-c-not%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현