Reputation: 140
ok, so lets say I need to process an order. We used to always have just 1 type of order, Order. Due to odd circumstances, we had to make our own injector, and are currently using it as so:
using(DependencyInjector.Inject()
.ForType<Order>()
.ImplementedBy<InsideOrderProcessor>())
{ ... };
Now we have a new order type or order, that requires subtle differences in processing. But it is still of type Order, and cannot be anything else. Is it ok to do something like:
using( isInsideOrder
? DependencyInjector.Inject()
.ForType<Order>()
.ImplementedyBy<InsideOrderProcessor>()
: DependencyInjector.Inject()
.ForType<Order>()
.ImplementedBy<OutisdeOrderProcessor>())
{ ... };
Will this even work? If so, is it ok to do?
Upvotes: 1
Views: 1952
Reputation: 633
It's acceptable to create the object outside of a using block (by whatever means you prefer) and then use it within the using block. In other words, it doesn't need to be instantiated inside the using block to use it in a using block.
Upvotes: 1
Reputation: 149030
It's okay in the sense that the code will compile, but it's not particularly readable. For the sake of writing code that's easy to maintain, I'd recommend refactoring this into a separate method. It should look a bit like this:
IOrderProcessor GetOrderProcessor(bool isInsideOrder)
{
if (isInsideOrder)
{
return DependencyInjector.Inject()
.ForType<Order>()
.ImplementedyBy<InsideOrderProcessor>();
}
else
{
return DependencyInjector.Inject()
.ForType<Order>()
.ImplementedBy<OutisdeOrderProcessor>();
}
}
And then you can write your using
like this:
using(this.GetOrderProcessor(isInsideOrder))
{
...
}
Upvotes: 6