FubuMVC: How to configure which ISessionState implementation to use - fubumvc

I have some trouble making Fubu use my own implementation of ISessionState.
My controller has a constructor that takes an ISessionState argument.
I have tried using StructureMap like so in my global asax
FubuApplication.For<ConfigureFubu>().StructureMapObjectFactory(container =>
{
container.Scan(scanner =>
{
scanner.TheCallingAssembly();
scanner.WithDefaultConventions();
});
container
.For<ISessionState>()
.Use<MySessionState>();
})
.Bootstrap();
Where and how am I supposed to tell Fubu to use MySessionState instead of SimpleSessionState?

#Pingvinen This should work as is. What's happening, exactly? I'm assuming you're getting SimpleSessionState injected instead of your implementation?
Just for kicks, you may try going into your ConfigureFubu class and modifying the services (in the constructor):
Services(x => x.ReplaceService<ISessionState, MySessionState>());

Related

Autofac resolve with different resolution for inner dependency

Let's assume the following classes
class Foo : IFoo {
Foo(IBar bar) {}
}
class Bar : IBar {
Bar(IBaz baz)
}
My container is set up so you can differentiate on IBaz by key.
builder.RegisterType<Baz1>().Keyed<IBaz>("1");
builder.RegisterType<Baz2>().Keyed<IBaz>("2");
Now I would like to create two classes who have an IFoo injected, but further down they need to be injected with either Baz1 or Baz2.
class MyClassA {
MyClassA(IFoo foo) {
var baz = foo.GetBar().GetBaz();
//baz should be of type Baz1
}
}
class MyClassB {
MyClassB(IFoo foo) {
var baz = foo.GetBar().GetBaz();
//baz should be of type Baz2
}
}
How do I configure/setup something like that? Preferable with an attribute in MyClassA and MyClassB.
Your question sort of hovers between two of our Autofac FAQs:
How do I pass a parameter to the middle of a resolve chain?: Because you're trying to resolve something at a top level (IFoo) but you want to specify the value somewhere in the middle of the chain, something that IFoo doesn't directly depend on.
How do I pick a service implementation by context?: Because you're trying to choose between two different IBar implementations based on where/how something elsewhere is being resolved.
It may not be the answer you want, but... in both of these cases, the answer is that there's an issue with the design that should be addressed rather than trying to force this to happen.
We explain why this is a design problem on the 'pass a parameter' FAQ. It says "parameter" but you could read the same thing as "resolving a specific implementation of an interface." I'll update/tweak the text so it applies here:
Technically speaking, you’re resolving an IFoo - a component that doesn’t need to know about the IBaz implementation. The implementation of IFoo could change, or even the implementation of IBar. You could register a stub for testing, or switch up how things work so that implementation tie isn't required.
Forcing the implementation tie of IBaz to the specific IFoo being required breaks the decoupling that interface-based development and inversion of control gives you by assuming that you "know" how the entire dependency chain is being resolved.
This is also basically the note on the 'implementation by context' FAQ. In that answer, there's a whole analogy using the object-oriented "animals" hierarchy to illustrate in a concrete fashion why it's not good. I'll not re-paste that here. However, I'll reiterate that treating these two IBaz implementations differently breaks the Liskov substitution principle - that you should be able to swap the IBaz implementations without breaking things. "Knowing" that one is substantially different than the other naturally implies that they're not the same and, thus, shouldn't implement the same interface. (Maybe a common base interface, but when they're consumed, the interface being consumed wouldn't be the same if the underlying implementation can't be treated the same.)
I recommend redesigning the interfaces so you don't have this problem. If that's not possible... well, honestly, there's not a much better solution for it than the answer you already posted. It's not easy to accomplish because it's not generally something you should try accomplishing.
Again, sorry that's probably not the answer you want, but I think that's the answer.
Well, this would do the trick.
builder.RegisterType<MyClass1>()
.WithParameter(
(pi, ctx) => pi.Name == "foo",
(pfoo, cfoo) => cfoo.Resolve<IFoo>(new ResolvedParameter(
(pbar, cbar) => pbar.Name == "bar",
(pbar, cbar) => cbar.Resolve<IBar>(new ResolvedParameter(
(pbaz, cbaz) => pbaz.Name == "baz",
(pbaz, cbaz) => cbaz.ResolveKeyed<IBaz>("1"))))))
.AsSelf();
builder.RegisterType<MyClass2>()
.WithParameter(
(pi, ctx) => pi.Name == "foo",
(pfoo, cfoo) => cfoo.Resolve<IFoo>(new ResolvedParameter(
(pbar, cbar) => pbar.Name == "bar",
(pbar, cbar) => cbar.Resolve<IBar>(new ResolvedParameter(
(pbaz, cbaz) => pbaz.Name == "baz",
(pbaz, cbaz) => cbaz.ResolveKeyed<IBaz>("2"))))))
.AsSelf();
However, I am not convinced that this is the preferred way for doing stuff like that.

LightInject - How to Register Multiple Interfaces to a Single Service?

How do I register a service that implements 4 interfaces?
For example: class Foo : IFoo, IBar, IApp, ISee { ... }
I was hoping for something like this:
container.Register<IFoo, IBar, IApp, ISee, Foo>();
But it appears this signature is for passing various types into a factory, in this case a factory that takes 4 parameters.
For those how also have this same question. Here is one possible way of solving it:
container.Register(_ => new Foo(), new PerScopeLifetime());
container.Register<IFoo>(factory => factory.GetInstance<Foo>());
container.Register<IBar>(factory => factory.GetInstance<Foo>());
container.Register<IApp>(factory => factory.GetInstance<Foo>());
container.Register<ISee>(factory => factory.GetInstance<Foo>());
In my specific case I also need to ensure that there was only one instance of Foo() within each scope. I.e. web request.

Moose - Why does Accessor defined in sub role does not satisfy parent role requires

I am defining an API using roles and also defining the implementation using roles. I combine multiple implementation roles into a class just before creating objects. I am running into an issue where accessor methods are not being recognized while normal methods are. Please see code below and errors received while running it. I wonder if this is an intended behavior or a bug?
Code:
use MooseX::Declare;
role api { requires qw(mymethod myattribute); }
role impl with api {
has myattribute => (is => 'ro', default => 'zz');
method mymethod { ...; }
}
class cl with impl {}
my $obj = cl->new;
Error:
'impl' requires the method 'myattribute' to be implemented by 'cl' at D:/lab/sbp
/perl/site/lib/Moose/Meta/Role/Application/ToClass.pm line 127
So the issue here (and I think it's being masked by MooseX::Declare) is a known issue where Role composition may happen before the methods are generated by the attribute. If you change your code to move the role composition to after the attribute declaration:
role impl {
has myattribute => (is => 'ro', default => 'zz');
with qw(impl);
method mymethod { ...; }
}
and the error goes away. I thought MooseX::Declare protected you against this by moving role composition to the end of the role/class declaration but it appears that isn't the case in this instance. Perhaps someone who uses MooseX::Declare more can illuminate better what's going on there.

What is the most efficient way to override an attribute in lots of my Moose based sub classes?

I am using HTML::FormHandler. To use it one is supposed to subclass from it and then you can override some attributes such as field_name_space or attribute_name_space.
However, I now have lots of forms all extending HTML::FormHandler or its DBIC based variant HTML::FormHandler::Model::DBIC and therefore have these overidden attributes repeated many times.
I tried to put them in a role but get an error that +attr notation is not supported in Roles. Fair enough.
What is the best way of eliminating this repetition? I thought perhaps subclassing but then I would have to do it twice for HTML::FormHandler and HTML::FormHandler::Model::DBIC, plus I believe general thought was that subclassing is generally better achieved with Roles instead.
Update: I thought it would be a good idea to give an example. This is what I am currently doing - and it involves code repetition. As you can see one form uses a different parent class so I cannot create one parent class to put the attribute overrides in. I would have to create two - and that also adds redundancy.
package MyApp::Form::Foo;
# this form does not interface with DBIC
extends 'HTML::Formhandler';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
...
package MyApp::Form::Bar;
# this form uses a DBIC object
extends 'HTML::Formhandler::Model::DBIC';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
...
package MyApp::Form::Baz;
# this form also uses a DBIC object
extends 'HTML::Formhandler::Model::DBIC';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
...
First of all, roles are composed into a class, they have nothing to do with subclassing. A subclass is a full class that extends a parent (or more than one, but in my experience multiple inheritance should be avoided if it can be). A role is a piece of behaviour, or a parial interface that can be applied to a class. The role then directly modifies the class. There's no new class created in general.
So inheritance and role composition are really two different things and two different kinds of design. Thus you can't simply exchange one for the other. Both have different design-implications.
My strategy with HTML::FormHandler has been to make a real subclass for each form that I require, and put the different behaviours of the form that I wanted to re-use into roles.
I'd think this question (how to implement the extensions you need in a clean and sane way) can't really be answered without knowing the actual design you're aiming for.
Update: I see what you mean and that's a tricky case. HTML::FormHandler is primarily targetted at extension by inheritance. So I think the best strategy would indeed be to have two subclasses, one for HTML::FormHandler and one for HTML::FormHandler::Model::DBIC. It seems teadious at first, but you might want to have different settings for them in the long run anyway. To avoid repeating the actual configuration (the default values) I'd try the following (this example is plain HFH, without DBIC):
package MyApp::Form;
use Moose;
use namespace::autoclean;
extends 'HTML::FormHandler';
with 'MyApp::Form::DefaultSettings';
# only using two fields as example
for my $field (qw( html_prefix field_traits )) {
has "+$field", default => sub {
my $self = shift;
my $init = "_get_default_$field";
my $method = $self->can($init)
or die sprintf q{Class %s does not implement %s method}, ref($self), $init;
return $self->$method;
};
}
1;
Note that you'd need to make an attribute lazy if it requires the values of another attribute for its computation. The above base class would look for hooks to find the initialized values. You'd have to do this in both classes, but you could put the default subroutine generation into a function you import from a library. Since the above doesn't require direct manipulation of the attribute anymore to change the default values, you can put that stuff in a role I called MyApp::Form::DefaultSettings above:
package MyApp::Form::DefaultSettings;
use Moose::Role;
use namespace::autoclean;
sub _build_html_prefix { 1 }
sub _build_field_traits { ['MyApp::Form::Trait::Field'] }
1;
This method will allow your roles to influence the default value construction. For example, you could have a role based on the one above that modifies the value with around.
There is also a very simple, but in my opinion kind-of ugly way: You could have a role provide a BUILD method that changes the values. This seems pretty straight-forward and easy at first, but it's trading extendability/flexibility with simplicity. It works simple, but also only works for very simple cases. Since the amount of forms in web applications is usually rather high, and the needs can be quite diverse, I'd recommend going with the more flexible solution.
The code for HTML::FormHandler::Model::DBIC is actually in a Moose trait in order to help with this situation. You can inherit from your base class, and in your forms that use the DBIC model, you can do
with 'HTML::FormHandler::TraitFor::Model::DBIC';
Would this method, using multiple inheritance (I know I know, ugh), where you put your common default overrides in one class, and then your customized code in others?
package MyApp::Form;
use Moose;
extends 'HTML::Formhandler';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
package MyApp::Form::Model::DBIC;
use Moose;
extends 'MyApp::Form', 'HTML::Formhandler::Model::DBIC';
# ... your DBIC-specific code
Now you can descend from MyApp::Form or MyApp::Form::Model::DBIC as needed.

How do I mock a Where clause in EF4

I am re-writing this question to make it clearer what I need to do. I am trying to use Rhino-Mock to test:
public IQueryable<TxRxMode> GetAllModes()
{
return m_context.TxRxModes.Where(txRxMode => txRxMode.Active);
}
Here's the code:
var context = MockRepository.GenerateStub<IProjectContext>();
//Returns an empty list
context.Expect(c => c.TxRxModes.Where(Arg<Func<TxRxMode, bool>>.Is.Anything)).Return(new List<TxRxMode>().AsQueryable());
TxRxModes in an IObjectSet property on the context and I want it to return an empty IQueryable<TxRxMode> object when the return m_context.TxRxModes.Where(txRxMode => txRxMode.Active); code is called.
When I run this, the Expect method call throws the an ArgumentNullException:
Value cannot be null.
Parameter name: predicate
I have tried the simpler:
IObjectSet<TxRxMode> modes = MockRepository.GenerateStub<IObjectSet<TxRxMode>>();
context.Expect(c => c.TxRxModes).Return(modes);
but this throws a null reference exception when I call
return m_context.TxRxModes.Where(txRxMode => txRxMode.Active);
Basically, this is part of the method I am trying to mock, so the key question is how do I mock this Where statement?
Where is actually a global static method and you shouldn't be mocking it. It operates on an IEnumerable however and you could just mock that.
Its kind of a hassle doing it with rhino mocks however. I would recommend doing the mock manually (if you need to do it at all).