Julian Rosebury
Julian Rosebury

Reputation: 61

Trying to new a ContextFactory in Program > public static void Main

I've tried to slim the code down here to focus on what I think to be the missing piece.

This is the "public static void Main(string[] args)" method of a console application.

As it's static I have to new-up the creditService and inject the Repository.

I just can't figure out how to create the financeRepository "IContextFactory< IFinanceContext > contextFactory" - I've left the expected input signature in the code below for explanation.

I've been going round in circles with this for days.

public static void Main(string[] args)
{
    IFinanceContext financeContext = new FinanceContext();
    IFinanceRepository financeRepository = financeContext(IContextFactory<IFinanceContext> contextFactory);

    ICreditService creditService = new CreditService(financeRepository);
    CreditHandler _creditHandler = new CreditHandler(creditService);

    _creditHandler.Handle();
}

Elsewhere in the solution, in another project, Ninject bootstraps it like this:

kernel.Bind<IContextFactory<IFinanceContext>>().ToFactory();
kernel.Bind<IFinanceContext>().To<FinanceContext>();

then where needed it's injected in via the constructor. So am I completely off base trying to new-up the Repository when there's a way to inject it in? I presumed I couldn't do that with a static method. Please help!

Upvotes: 0

Views: 334

Answers (1)

YuvShap
YuvShap

Reputation: 3835

Have you considered using Ninject.Extensions.Factory? It seems it fits very well for your needs. It is very powerful tool but the basics are very simple, you can browse the documentation which is great.

Here some resources to get started with :

https://github.com/ninject/Ninject.Extensions.Factory/wiki/Factory-interface

http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/

Upvotes: 1

Related Questions