How can I resolve dependency in Castle Windsor Factory? - asp.net-mvc-4

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

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.

Using Ninject WhenInjectedInto

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();

Querying using OData and asp.net MVC webapi against a NHibernate database

I doubt this is just specific to NHibernate. But I have code as follows....
public class ClientController : ApiController
{
// GET /api/<controller>
public IQueryable<Api.Client> Get()
{
return Repositories.Clients.Query().Select(c => Mapper.Map<Client, Api.Client>(c));
}
I basically want to Query the database using the Odata criteria.... get the relevant 'Client' objects, and the convert them to the DTO 'Api.Client'.
But... the code as is, doesn't work. Because NHibernate doesn't know what to do the with the Mapper.... It really wants the query to come before the .Select. But I'm not sure I can get the Odata Query first?
It will work if I do
return Repositories.Clients.Query().Select(c => Mapper.Map<Client, Api.Client>(c)).ToList().AsQueryable();
But that's a bit sucky as you have to get ALL the clients from the database to do the OData query on.
Is there anyway to get the "Select" to happen after the OData query? Or another way to approach this?
I did not test it yet but the Open Source project NHibernate.OData could be useful for you.
The problem is that you are trying to execute C# code (Mapper.Map) inside the NH call (that is translated to SQL)
You'd have to map Api.Client manually, or create a Mapper implementation that returns an Expression<Func<Client, Api.Client>> and pass it directly as a parameter to Select().
Even with that, I'm not sure if NHibernate will translate it. But you can try.
AutoMapper supports this scenario with the Queryable Extensions
public IQueryable<Api.Client> Get() {
return Repositories.Clients.Query().Select(c => Mapper.Map<Client, Api.Client>(c));
}
becomes
public IQueryable<Api.Client> Get() {
return Repositories.Clients.Query().ProjectTo<Api.Client>(mapper.ConfigurationProvider);
}

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

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
}