Using Ninject WhenInjectedInto - ninject

I'm trying to do the following:
kernel.Bind<IUnitOfWork>().To<UnitOfWork<OrderDbContext>>().WhenInjectedInto<OrderRepository>()
.InRequestScope();
kernel.Bind<IUnitOfWork>().To<UnitOfWork<OrderDbContext>>().WhenInjectedInto<InvoiceRepository>()
.InRequestScope();
kernel.Bind<IUnitOfWork>().To<UnitOfWork<OrderDbContext>>().WhenInjectedInto<PayslipRepository>()
.InRequestScope();
What I want to logically happen is that a single instance of UnitOfWork<OrderDbContext> is created for the request, and injected as IUnitOfWork into any of OrderRepository, InvoiceRepository or PayslipRepository.
Instead what is happening is that a new instance of UnitOfWork<OrderDbContext> is created for each of the repositories.
I think if I replace the IUnitOfWork constructor paramter on those repositories for new 'dummy' IOrderUnitOfWork, IInvoiceUnitOfWork and IPayslipUnitOfWork interfaces that simply inherit IUnitOfwork and bind against those in Ninject's config then it should work, but I don't want to create empty dummy interfaces just to get Ninject working :(
I was looking for something like:
kernel.Bind<IUnitOfWork>().To<UnitOfWork<OrderDbContext>>().WhenInjectedInto<OrderRepository, InvoiceRepository, PayslipRepository>()
.InRequestScope();
but that doesn't exist, and I couldn't find any chainable methods to get the same working either.
Your help much appreciated!

Try making a new UnitOfWork and bind it IUnitOfWork as a constant:
UnitOfWork<OrderDbContext> work = new UnitOfWork<OrderDbContext>;
kernel.Bind<IUnitOfWork>().ToConstant(work).WhenInjectedInto<OrderRepository>().InRequestScope();
kernel.Bind<IUnitOfWork>().ToConstant(work).WhenInjectedInto<InvoiceRepository>().InRequestScope();
kernel.Bind<IUnitOfWork>().ToConstant(work).WhenInjectedInto<PayslipRepository>().InRequestScope();

Related

Yii dependency injection basic

Can anyone explain me DI basics please? I understand what it is, but I don't really know now, how to use DI container in practice. For example, I have 2 functions in the same controller:
public function actionIndex()
{
$productsModel = new Products();
$productsFormModel = new ProductsForm();
$informationFormModel = new InformationForm();
....
}
public function actionInformation()
{
$productsModel = new Products();
$productsFormModel = new ProductsForm();
$informationFormModel = new InformationForm();
....
}
So my two questions is:
As you see above, I use same models in these functions. It is good idea to initialized them into "public function init() {}" and then use them in all class globally or this is bad idea?
I think it should be better if these models would be injected into this controller, right? How to do it correctly?
I was created file DI.php, which I included into entry script. File content was:
<?php
\Yii::$container->set('products_model', 'app\models\Products');
\Yii::$container->set('products_form', 'app\models\ProductsForm');
\Yii::$container->set('information_form', 'app\models\InformationForm');
?>
So then I was able to get class app\models\Products instance globally (in every controller, view or model):
$instance_products = \Yii::$container->get('products_model');
$instance_products_form = \Yii::$container->get('products_form');
$instance_information_form = \Yii::$container->get('information_form');
But this is bad idea, right?
Please, answer someone my two questions. :)
Thanks!
Keeping things DRY is always a good idea. The classes seem very related, so I suggest making this relationship explicit by creating a new model (e.g. ProductsInfo). One could name the controller accordingly (ProductsInfoController), thereby clarifying the application structure.
Use dependency injection sparingly. If there is a different way way, use that instead. DI isn't a good fit for the described use-case.

How can I resolve dependency in Castle Windsor Factory?

I read about factories in CastleWindsor but I cannot get it clear. Hope anyone could help me.
I have this typed factory in an MVC4 project.
public interface IOrderProcessorFactory
{
T Create<T>(string ProcessorName) where T : IOrderProcessor;
void Release(object service);
IOrderProcessor GetTakeAway();
IOrderProcessor GetInLocal();
}
this is register this way:
container.Register(Component.For<IOrderProcessorFactory>).AsFactory();
container.Register(Component.For<IOrderProcessor>).ImplementedBy<TakeAwayOrderProcessor>().LifestylePerWebRequest().Named("TakeAway"));
container.Register(Component.For<IOrderProcessor>().ImplementedBy<InLocalOrderProcessor>().LifestylePerWebRequest().Named("InLocal"));
If inside an MVC controller I call the factory in this way.
_orderProcessorFactory.GetTakeAway();
I get the correct one, the one named "TakeAway".
But for this I have to previous know the type. In other words, I want to call the factory get methods and pass a "name" and the factory returns the correct one.
For example in pseudo-code I want this
TakeAwayOrderProcessor processor1 = factory.GetMeProcessorCalled("TakeAway")
InLocalOrderProcessor processor2 = factory.GetMeProcessorCalled("InLocal")
I know I can pass parameters to the constructor but then I will have to select it "manually" with if name is this return this one else...
Is there any way Windsor can do this automatic, like StructureMap do with:
ObjectFactory.GetNamedInstance<IOrderProcessor>("InLocal");
You need a TypedFactoryComponentSelector

FlexNativeMenu with robotlegs

I an using the Robotlegs framework and I am busy with an AIR desktop application and I want to use FlexNativeMenu. THe problem is that I am not able to create a view class based on mx.controls.FlexNativeMenu for dependency injection. When not using Robotlegs the code is pretty straightforward - any help will be appreciated. Thanks.
generally you can use whatever you want to a view. The problem is that the mediator's onRegister method will be called only if your view dispatches ADDED_TO_STAGE event. And because FlexNativeMenu doesn't fire this event your mediator is not working (http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/controls/FlexNativeMenu.html#eventSummary)
for RobotLegs v2
If you're trying to inject into the FlexNativeMenu (hereinafter referred to FNM), you can try something like this (I'd do this in your IConfig implementor):
injector.injectInto( fnmInstance );
If you are trying to inject an instance of FNM (say in it's mediator):
[Inject]
public var view:MyFNMClass;
If you are trying to attach a mediator to the FNM instance you do something like this in your IConfig implementor:
//requires that you map the FNM (assuming you're subclassing it)
mediatorMap.map( MyFNMClass ).toMediator( MyFNMClassMediator );
//else where where you decide to wire it up
mediatorMap.mediate( fnmInstance );
The "gotcha" is this: There isn't a very pretty way to access the FNM prior to injection. I grabbed it like so:
//very nasty I know
var fnm:MyFlexNativeMenu = FlexGlobals.topLevelApplication.myMenu;
code
Made a git repo - https://github.com/jusopi/RobotLegs-v2-FlexNativeMenu-example

objectcontext vs datacontext

i'm just new in developping silverlight, and i created a linq to sql connection and a service domain class. I want to get data from 2 tables which have a 1 to many relation into a datagridview. To do this i need to state include commands in my metadata and service domain class , but to do this i need to have an objectcontext instead of a datacontext(that i'm currently having ) can someone help me with this matter so i can use the include statement to get querys for my detail-grid
edit:
I've done what u said added the
"<IncludeAttribute()> _"
Public Property SubgroepIndustries As EntitySet(Of SubgroepIndustrie)
but i get this error message:
Error 1 'Include' is not a member of 'System.Data.Linq.Table(Of ILA4.HoofdgroepIndustrie')
edit 2:
when i try to use the include in my domain service class not the metadata so
Return Me.DataContext.HoofdgroepIndustries.Include("SubgroepIndustries")
doesnt work
ObjectContext is a class that is generated inside the generated DomainService class that you made.
Just do a this.ObjectContext in the DomainService class you made and you should have access to the class you are looking for.
I have assumed here that you are using RIA services and your DomainService MetaData class is tagged with [Include] attributes. Otherwise doing this.ObjectContext.SomeEntity.Include("ChildEntity") will not work out.
Edit:
Add <IncludeAttribute()> _ to Public Property SubgroepIndustries As EntitySet(Of SubgroepIndustrie) in your .metadata.vb
As for ObjectContext, looking at your code you don't need ObjectContext I think. Use DataContext instead.
so for example:
Public Function GetHoofdgroepIndustries() As IQueryable(Of HoofdgroepIndustrie)
Return Me.DataContext.HoofdgroepIndustries.Include("SubgroepIndustries")
End Function
is how you will do it.
Edit 2: You need Imports System.ServiceModel.DomainServices.Server for <IncludeAttribute()>

NHibernate DTO Parent child relation

I have som entities and now want to make some DTO´s based on there entities using nhibernate.
I have a Service - Allocation -Ressource where allocation describes how the ressource is allocated for the service.
I want a DTO like
ServiceDTO
-Name
-RessourceDTO
where RessourceDTO also has a name.
In the examples I have see for NHibernate projection/DTO you either use properties or constructor. If I use The Constructor approach I would have something like
ServiceDTO(Name, List
But I can't figure out how to make this work.
Another approach is to extract all the services and then loop through them and hit the database each time, or extract a larger result and then make the DTO's
What is the best approach? I going to hide all of this inside a repository.
How about
public ServiceDTO GetDTOFor(int Id);
{
var service = Session.CreateCriteria<Service>()
.Add(Restrictions.Eq("Id", id)
.SetFetchMode("Resources", fetchmode.eager) // eager load resources
.uniqueResult<Service>();
return new ServiceDTO(service.Name, service.Resources.ToList()) // Copy the Resources
}