Autofac resolve with different resolution for inner dependency - autofac

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.

Related

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.

why not using method call instead of using properties?

I'm studying Swift language, and in github.com, i found SwiftHelper.
In it's IntHelper.swift file, I found below code:
extension Int {
var isEven: Bool {
let remainder = self % 2
return remainder == 0
}
var isOdd: Bool {
return !isEven
}
}
why isEven and isOdd were written as properties, not method calls?
In this situation, Using property has any advantage over using method calls?
In purely technical terms, there are no advantages or disadvantages to using a property over a method or vice versa* : the only difference is in readability.
In this particular case, I think that using an extension property makes for better readability than using a method call, because it reads better. Compare
if myInt.isOdd {
... // Do something
}
vs.
if myInt.isOdd() {
... // Do something
}
vs.
if isOdd(myInt) {
... // Do something
}
The first (property) and second (method) code fragments keeps words in the same order as they are in English, contributing to somewhat better readability. However, the second one adds an unnecessary pair of parentheses. For completeness, the third way of accomplishing the same task (a function) is less readable than the other two.
* This also applies to other languages that support properties, for example, Objective-C and C#.
The properties used in the extension are what's known as 'computed properties' - which in a lot of ways are like a method :) in that they don't store any state themselves, but rather return some computed value.
The choice between implementing a 'property' vs. a 'method' for something like this can be thought of in semantic terms; here, although the value is being computed, it simply serves to represent some information about the state of the object (technically 'struct' in the case of Int) in the way that you would expect a property to, and asking for that state isn't asking it to modify either itself or any of its dependencies.
In terms of readability, methods in Swift (even those without arguments) still require parens - you can see the difference that makes in this example:
// as a property
if 4.isEven { println("all is right in the world") }
// as a method
if 5.isEven() { println("we have a problem") }

anybody doing a class tree in Dart?

Darts Mirrors are for me currently poorly documented and very difficult to experiment with - they behave differently in code than from within the console.
for my own use, I would love to be able to treat classes (Types) as a trees, with a node being something like:
class Node {
type ... <== Type itself
name ... <== name of current class
super ... <== super of this class, eg, extends super
mixins ... <== mixins used to build this Type
extendChildren ... <== Types for which this type is super
mixinChildren ... <== Types for which this type is a mixin
}
for the life of me, I cannot get something this basic out of current Mirrors. hoping that somebody smarter than me has given it a shot!!
Below is a simple example which prints the name of the superclass and the name of Foo's members.
Note that the API uses Symbols, not strings. These are required so that dart2js can minify code that uses mirrors, they're a bit of a pain, but they mean that your code will run cross browser, and be compact.
To convert between symbols and strings see MirrorSystem.getName() and MirrorSystem.getSymbol() (Actually I believe you can just use new Symbol('foo') now).
Also note a new feature was recently added giving a special literal syntax for symbols. Up until recently you needed to type const Symbol('foo'), now just #foo, you may see a mix of old an new when looking at examples.
See this article for more information about mirrors.
Warning - probably a few typos in the example.
import 'dart:mirrors';
class Bob {
}
class Foo extends Bob {
String bar = 'jim';
}
main() {
var classMirror = reflectClass(Foo);
print(MirrorSystem.getName(classMirror.superClass.simpleName));
classMirror.declarations.values.forEach((d) => print(MirrorSystem.getName(d.simpleName)));
}
Update: Based on what Alan said below (Also untested):
Example source:
library foo;
class B extends A {
}
class A {
}
Definition:
List<ClassMirror> findSubClasses(Symbol libraryName, ClassMirror superClass) =>
currentMirrorSystem().findLibrary(libraryName).declarations.values
.where((d) => d is ClassMirror
&& d.superClass.simpleName == superClass.simpleName);
Usage:
var cm = reflectClass(A);
var subclasses = findSubClasses(#foo, cm);
There is a #MirrorsUsed attribute that you may want to experiment with if you're interested on compiling to js. It's still experimental so expect this to change.

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.

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.