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

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.

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.

FubuMVC: How to configure which ISessionState implementation to use

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

Fields in CoffeeScript?

class #A
A_Function_Alias: => #my_function
my_function: =>
usage_of_alias: =>
#A_Function_Alias.call()
What i want, is usage_of_alias to be
usage_of_alias: =>
#A_Function_Alias
And have it behave the same. i.e. I want a more functional style syntax here. I've tried multiple combinations with no success. The fact that i have to evaluate my function to get the goodies inside bothers me.
One application would be instead of this:
event: => new Event(#my_function)
which is accessed as event.call().hi()
i could have some other declaration that would allow me to access event as event.hi()
Something that behaves more like a field instead of a property.
I'm thinking you want this:
class #A
my_function: => alert 'my function!'
A_Function_Alias: #::my_function
usage_of_alias: =>
#A_Function_Alias()
# some other code...
See what this compiles to here.
When evaluating a class # is the class constructor object, the class object itself. And the :: operator lets you drill into the prototype. So #::foo in a class body compiles to MyClass.prototype.foo.
So what this is doing is first making a normal instance method named my_function, defined on A.prototype.my_function. Then we make a new instance method named A_Function_Alias and directly assign the function from class objects prototype that we just created. Now my_function and A_Function_Alias both point to the exact same function object.
But as a more sane alternative, might I suggest a pattern that defines a private inner function that the class can use, and then assigning it more directly, without crazy the prototype accessing?
class #A
# Only code inside this class has access to this local function
innerFunc = -> alert 'my function!'
# Assign the inner funciton to any instance methods we want.
my_function: innerFunc
A_Function_Alias: innerFunc
usage_of_alias: =>
#A_Function_Alias()
# or
#my_function()
# or
innerFunc()
# they all do the same thing

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.

Need help understanding Generics, How To Abstract Types Question

I could use some really good links that explain Generics and how to use them. But I also have a very specific question, relater to working on a current project.
Given this class constructor:
public class SecuredDomainViewModel<TDomainContext, TEntity> : DomainViewModel<TDomainContext, TEntity>
where TDomainContext : DomainContext, new()
where TEntity : Entity, new()
public SecuredDomainViewModel(TDomainContext domainContext, ProtectedItem protectedItem)
: base(domainContext)
{
this.protectedItem = protectedItem;
}
And its creation this way:
DomainViewModel d;
d = new SecuredDomainViewModel<MyContext, MyEntityType>(this.context, selectedProtectedItem);
Assuming I have 20 different EntityTypes within MyContext, is there any easier way to call the constructor without a large switch statement?
Also, since d is DomainViewModel and I later need to access methods from SecuredDomainViewModel, it seems I need to do this:
if (((SecuredDomainViewModel<MyContext, MyEntityType>)d).CanEditEntity)
But again "MyEntityType" could actually be one of 20 diffent types. Is there anyway to write these types of statements where MyEntityType is returned from some sort of Reflection?
Additional Info for Clarification:
I will investigate ConstructorInfo, but I think I may have incorrectly described what I'm looking to do.
Assume I have the DomainViewModel, d in my original posting.
This may have been constructed via three possible ways:
d = new SecuredDomainViewModel<MyContext, Order>(this.context, selectedProtectedItem);
d = new SecuredDomainViewModel<MyContext, Invoice>(this.context, selectedProtectedItem);
d = new SecuredDomainViewModel<MyContext, Consumer>(this.context, selectedProtectedItem);
Later, I need to access methods on the SecuredDomainViewModel, which currently must be called this way:
ex: if (((SecuredDomainViewModel<MyContext, Order)d).CanEditEntity)
ex: if (((SecuredDomainViewModel<MyContext, Invoice)d).CanEditEntity)
ex: if (((SecuredDomainViewModel<MyContext, Consumer)d).CanEditEntity)
Assuming I have N+ entity types in this context, what I was hoping to be able to do is
something like this with one call:
ex: if (((SecuredDomainViewModel<MyContext, CurrentEntityType)d).CanEditEntity)
Where CurrentEntityType was some sort of function or other type of call that returned Order, Invoice or Consumer based on the current item entity type.
Is that possible?
You can create a non-generic interface that has the CanEditEntity property on it, make SecuredDomainViewModel inherit off that, then call the property through the interface...
Also, the new() constructor allows you to call a constructor on a generic type that has no arguments (so you can just write new TEntity()), but if you want to call a constructor that has parameters one handy trick I use is to pass it in as a delegate:
public void Method<T>(Func<string, bool, T> ctor) {
// ...
T newobj = ctor("foo", true);
// ...
}
//called later...
Method((s, b) => new MyClass(s, b));
I can't help on the links, and likely not on the type either.
Constructor
If you have the Type, you can get the constructor:
ConstructorInfo construtor = typeof(MyEntityType).GetConstructor(new object[]{TDomainContext, ProtectedItem});
Type
I'm not really sure what you're looking for, but I can only see something like
if (((SecuredDomainViewModel<MyContext, entityType>)d).CanEditEntity)
{
entityType=typeof(Orders)
}
being what you want.