in a WPF application I'm using Caliburn Micro for MVVM pattern... I want to try another IoC and want to reuse the most of the existing code...
In my application I've defined all the exportable class via attribute as
[Export(typeof(ITaggable))]
[Export(typeof(CorporateActionViewModel))]
[Export(typeof(IScreen))]
public class CorporateActionViewModel :...
How can I register them without doing manually
ContainerInstance.Register<ITaggable, CorporateActionViewModel>();
ContainerInstance.Register<IScreen, CorporateActionViewModel>();
ContainerInstance.Register<CorporateActionViewModel, CorporateActionViewModel>();
Another question is regarding the Lazy initialization... I've read here how to register lazy... but do I have to call the Container.Verify() or not?
Thanks
The use of the ExportAttribute thoughout your complete source just to register all your types sounds like a violation of the Dependency Inversion Principle. Which is on its own questionable but it has several disadvantages for sure.
Simple Injector has no need for using attributes to find the classes you want to register. It is actually one of the design principles
of the Simple Injector crew.
You could easily (well easy... depending on your current design offcourse...) remove the attribute if you follow the SOLID principles for your viewmodels (and corresponding views).
If we take a typical LoB application where we have a bunch of entities in a database we could split our viewmodel/view design in these generic interfaces which your viewmodels will implement (one at a time offcourse):
//for a typical datagrid view of your entities with e.g. Add, Edit and Delete button
IWorkspace<TEntity>;
//for a typical edit view for one entity (including possible child entities)
IEditEntity<TEntity>;
//for choosing a specific foreign entity type from your edit view
//e.g. your editing an order and need to specify the customer
IChooseEntity<TEntity>
Using these we will get very specific viewmodels which are SOLID and which still could be composed to a very big complicated view for the user if you wish.
You could register these types very easily with Simple Injector using a batch registration like this:
container.RegisterManyForOpenGeneric(
typeof(IChooseEntityViewModel<>), Assembly.GetExecutingAssembly());
As a bonus of this design you could wrap your viewmodels with one or more decorators which could be used to some real MVVM stuff like find your view, bind it to the viewmodel and show the view in window/page etc.
If you want to read more about decorators, in combination with simple injector you can find some nice articles here (don't forget the various links).
This query will find all types marked with ExportAttribute
private IEnumerable<Type> GetExportedTypes()
{
return from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where Attribute.IsDefined(type, typeof(ExportAttribute))
select type;
}
And this query will find all the services published for a type using ExportAttribute
private IEnumerable<Type> GetServicesFromType(Type type)
{
return from attribute in Attribute
.GetCustomAttributes(type, typeof(ExportAttribute))
select ((ExportAttribute)attribute).ContractType;
}
These queries can be used something like this
var container = new Container();
foreach(var type in GetExportedTypes())
{
foreach (var service in GetServicesFromType(type))
{
container.Register(service, type);
}
}
container.Verify();
As for your question regarding Verify()? It is never mandatory to call Verify but it is always advised. The Diagnostic Services are there to help.
If you explicitly register both the lazy and the normal version of a registration, your object graph will still be fully verifiable. Take a look at this registration:
container.Register<ITaggable, CorporateActionViewModel>();
container.Register<Lazy<ITaggable>>(
() => new Lazy<ITaggable>(container.GetInstance<ITaggable>));
container.Verify();
Verify will walk through all explicit registrations and tries to create an instance for each of the registrations. This means that it will create a Lazy<ITaggable> instance. Of course being able to create an Lazy<ITaggable> doesn't mean that the CorporateActionViewModel can be created, but Simple Injector will also verify the ITaggable registration. Those two together make sure that your complete DI configuration is verifiable.
The following configuration however will give you a false sense of security:
container.Register<Lazy<ITaggable>>(
() => new Lazy<ITaggable>(container.GetInstance<CorporateActionViewModel>));
container.Verify();
Here the Lazy<ITaggable> registration uses the GetInstance<CorporateActionViewModel> as factory method, but CorporateActionViewModel is not registered explicitly. During verification, Simple Injector will create the Lazy<ITaggable> which will obviously succeed, but it will not automatically call the Lazy<T>.Value property for you (which is deliberate, because there might be a reason why you postponed the creation of the object graph).
But please reconsider your strategy of injecting Lazy throughout your code base. This is a bad idea and bad practice. Please read this and this for more information.
And in answer to your second question. (Did you know you could edit your original question. This keeps things understandable)
I think I can refactor it to
ContainerInstance.RegisterSingle<ISharedModuleObject>(
new SharedModuleObject { DataLavorativa = DateTime.Today,
DataLavorativaPrecedente = DateTime.Today });
But is this ok?
I do not think so. Your calling it a factory, so RegisterSingle(), which registers a singleton instance is not ok.
I think your implementation should be:
public class SharedModuleObject : ISharedModuleObject
{
public SharedModuleObject()
{
this.DataLavorativa = DateTime.Now;
this.DataLavorativaPrecedente = DateTime.Now;
}
public DateTime DataLavorativaPrecedente { get; set; }
public DateTime DataLavorativa { get; set; }
}
and register it like:
ContainerInstance.Register<ISharedModuleObject, SharedModuleObject>();
This will register a transient instance of the SharedModuleObject. So you get a new instance every time it resolved from the container.
Edit:
From your comment I understand you actually need a singleton. In that case your code was ok, but this seems to be a little cleaner to me:
ContainerInstance.RegisterSingle<ISharedModuleObject, SharedModuleObject>();
Related
MVVM, using PRISM 6 and Unity.
Bootstrapper takes care of creating intial View, which is in turn AutoWired to the ViewModel (i.e. View Model is resolved and it's DI's are taken care of).
Now the View Model has a Collection of other View Models.
This Collection can be added to with User Input, say with a button push.
The View Models in the collection require access to a singleton that I have to manage the "Workspace" (paths for image folders etc). So I would also want the creation of those objects to have that "Workspace" singleton injected into it.
In the method that would create a new ViewModel, what's the correct way to utilize DI/IoC to create it?
The only way I see it (dangerous to say "only" I know, that's why I'm asking for help) is:
Inject the Unity Container into the View Model that contains the
collection, then Resolve the new View Models as the button is hit.
The new View Models would be setup with a dependency on the
interface for the "Workspace" object.
Create a new View Model when the button is hit and pass the
"Workspace" into the constructor (of course the Workspace would need to be DI'd into the parent View Model to be passed down).
I have read multiple places that getting into passing the Container down via DI so that one can use Resolve<> isn't "correct".
Is this where creating a generic Factory would help? This still forces me to pass the container down, now it's just in the form of a factory though...
public T factory<T>(IContainer _container)
{
return _container.Resolve<T>();
}
Often when I read about DI, it is treated as the be all and end all. I more often than not use IoC heavily even in my small and simple projects, however, it is just pattern and has a place like everything else.
The Microsoft Press book Adaptive Code via C# explains SOLID well, justifies its use, covers the various forms of DI and the cost/benefit of each technique. For me, it made a lot of sense of these issues, managing project growth, and dealing with external dependencies.
I would NOT pass the UnityContainer to anything outside of my bootstrapper, other than a system which abstracts and breaks apart the bootstrapping/modularity process. In addition to the points you have made about this, Unity is a third-party dependency to your application just like anything else, and I would be very selective of which (if any) I tie myself to.
For your example above, I would use a simple factory. You could abstract this as far as you like, but a good compromise would be relieving your primary ViewModel of the burden of having to create its own children.
When using DI, there is nothing wrong with instantiating things yourself where appropriate. The most appropriate place of course is a factory. I wouldn't create a generic factory, as you stated, this is basically just like passing around the IoC container. Define a typed factory instead:
public interface IWorkspaceItemViewModelFactory
{
WorkspaceItemViewModel CreateWorkspaceItem();
}
The implementation of this might look something like this:
public class WorkspaceItemViewModelFactory
{
private readonly IWorkspaceManager _workspaceManager;
public WorkspaceItemViewModelFactory(IWorkspaceManager workspaceManager)
{
_workspaceManager = workspaceManager;
}
public WorkspaceItemViewModel CreateWorkspaceItem()
{
return new WorkspaceItemViewModel(_workspaceManager);
}
}
This class is an information expert with the single responsibility of creating WorkspaceItemViewModel instances. It has the right the use the new keyword, and have knowledge of WorkspaceItemViewModel dependencies. You may wish to insulate the ViewModel with an interface, but the value might be very little in your use case. Ultimately, you are using IoC, DI, and Interface Segregation for a reason, and when they stop delivering value to your particular application their use becomes noise.
Your view model could make use of this something like:
public class ExampleViewModel : ViewModelBase
{
public ExampleViewModel(IWorkspaceItemViewModelFactory workspaceItemViewModelFactory)
{
AddItemCommand = new ActionCommand(() =>
{
var newItem = workspaceItemViewModelFactory.CreateWorkspaceItem();
WorkspaceItems.Add(newItem);
});
}
public ICommand AddItemCommand { get; }
public ObservableCollection<WorkspaceItemViewModel> WorkspaceItems { get; } = new ObservableCollection<WorkspaceItemViewModel>();
}
I want to let Ninject resolve an instance of T based on a specific enum input value.
I have read about Ninject's factory extension, but I couldn't find any example having the factory resolve a specific class based on an enum.
Each class derives from a base class and that derived class has several, different interfaces that Ninject also has to resolve.
For example this is how the interface should look like:
public interface IProcessFactory
{
T Create<T>(ProcessIndex processIndex) where T : BaseProcess;
}
How can this be achieved ?
This is not supported out of the box. You can customize it by writing your own implementation of IInstanceProvider(also see ninject Wiki entry. Then configure it for your specific factory:
kernel.Bind<IFooFactory>()
.ToFactory(() => new MyCustomInstanceProvider());
Or alternatively, if you want to change the behavior of all .ToFactory() bindings: Rebind IInstanceProvider after loading Ninject.Extensions.Factory:
kernel.Rebind<IInstanceProvider>().To<MyCustomInstanceProvider>();
However, if it's not something you need often i would consider manually writing a factory implementation # composition root.
Anyway, in both cases you'll need to know how to create a conditional binding. Ninject calls it Contextual Binding.
One method is to use Binding-Metadata:
const string EnumKey = "EnumKey";
Bind<IFoo>().To<AFoo>()
.WithMetadata(EnumKey, MyEnum.A);
IResolutionRoot.Get<IFoo>(x => x.Get<MyEnum>(EnumKey) == MyEnum.A);
Another way would be to create a custom IParameter and use in a conditional binding:
Bind<IFoo>().To<AFoo>()
.When(x => x.Parameters.OfType<MyParameter>().Single().Value == A);
There are several options available to implement AbstractFactory using DI (Ninject).
After analyzing the options, I came up with the solution provided by Mark Seemann, see http://blog.ploeh.dk/2012/03/15/ImplementinganAbstractFactory/
The Container Based Factory solution is the one I chose, because:
Performance: on demand DI resolve on request, no instances loaded in the constructor
Easy for refactor: when we want to replace the current DI framework (Ninject) to a much better performer with (almost or even better) featureset, the only place to change are the calls inside the factory and not in the NinjectModules/Composition Root.
See also at SO:
Simple Injector:Factory classes that need to create classes with dependencies
I'm working on a project that's using the MS Application Blocks. I see the 'Unity' dll is available to me. It's version 1.1 by the way. How can I use dependency injection here?
I have a class
public class ScheduleDataDetailsDC
{
public int ScheduleID;
public List<ScheduleRateLineItem> MinRateList;
public List<ScheduleRateLineItem> MaxRateList;
public List<ScheduleRateLineItem> VotRateList;
public List<ScheduleLOSRateDC> LosRateList;
public List<ScheduleRateParamsDC> RateParams;
}
So when I new it up I am doing this...
new ScheduleDataDetailsDC{
LosRateList = new List<ScheduleLOSRateDC>()
, MaxRateList = new List<ScheduleRateLineItemDC>()
, MinRateList = new List<ScheduleRateLineItemDC>()
, RateParams = new List<ScheduleRateParamsDC>()
, VotRateList = new List<ScheduleRateLineItemDC>()
}
Can Unity 1.1 Help me in anyway here? I would like to just be able to use var x = new ScheduleDetailsDC(), and those 5 inner lists be initialized for me. Can Unity do anything for me here? Please note I've never used DI before.
Thanks for any pointers,
~ck in San Diego
The best thing to do would be to initialise the lists in the constructor and deny direct access to them from other classes by making them into properties:
public class ScheduleDataDetailsDC
{
public ScheduleDataDetailsDC()
{
this.MinRateList = new List<ScheduleRateLineItem>();
//inialise other lists
}
public List<ScheduleRateLineItem> MinRateList { get; private set; }
...
}
It doesn't seem as though dependency injection can really be of use here since the class seems to be a simple data container, although it's difficult to tell without more context.
Yes Unity can help you, but I think it's not the case. You can just initialize your lists incide your object giving them default instances, Unity as any other IoC container shouldn't be used as a simple object builder (despite it could).
I'm not sure specifically what the details of the 1.1 release of Unity are, but generally speaking whenever you are using an Inversion of Control Container, you have to go through the following steps:
Register the types your IoC container (Unity in your case) knows about. This includes all of the main types that you plan to request, plus all of the dependent types. In your case you will need to let it know about ScheduleDataDetailsDC, and what, exactly needs to go into each of the lists that are considered dependencies
Your types should specify all of the required dependencies as constructor arguments. This is what the IoC Container will look at to determine what needs to be injected. If you have optional dependencies then you can use Property Injection to support that (if your IoC container supports it, which I think Unity does)
You must request an instance of your registered type from the container. How exactly you do this depends on you container. There should be a method like Get<T>() or Resolve<T>. Generally your going to request instances of the "Highest Level" classes, i.e the ones that are used somewhere near the entry point for your software. If you do this, and you have applied Dependency Injection for all dependent classes down the line (and you've correctly registered all of the dependent types) you should get an object with all of it's dependencies supplied, and likewise all of that objects dependencies should be supplied, and on down the line.
You also tend to see Interfaces used in conjunction with IoC a lot since you can bind a concrete type to the interface type, and then specify that interface as your dependency. This allows you to apply business rules and configuration values during the binding process that will give you the ability to use different concrete implementations in cases where you would need to do such a thing.
So given all of this, it's hard to say exactly what would be involved in utilizing Unity in the situation you've outlined above. Firstly you would need to register ScheduleDataDetailsDC, but to get the dependencies in place you would also need to register each of the List types, or more specifically each concrete object that would go in each list (and then, of course all of the dependencies for those classes). Since I'm not really sure what the roles of those lists are, it's hard for me to say how you could go about doing that (or even if you could go about doing that).
I'm working on a module that requires a strictly decoupled interface. Specifically, after instantiating the root object (a datasource), the user's only supposed to interact with the object model via interfaces. I have actual factory objects (I'm calling them providers) to supply instances that implement these interfaces, but that left the clumsiness of getting the providers. To do so, I've supplied a couple methods on the datasource:
public class MyDataSource
{
private Dictionary<Type, Type> providerInterfaceMapping = new Dictionary<Type, Type>()
{
{ typeof(IFooProvider), typeof(FooProvider) },
{ typeof(IBarProvider), typeof(BarProvider) },
// And so forth
};
public TProviderInterface GetProvider<TProviderInterface>()
{
try
{
Type impl = providerInterfaceMapping[typeof(TProviderInterface)];
var inst = Activator.CreateInstance(impl);
return (TProviderInterface)inst;
}
catch(KeyNotFoundException ex)
{
throw new NotSupportedException("The requested interface could not be provided.", ex);
}
}
}
I've modified some details on the fly to simplify (e.g., this code snippet doesn't include the parameters passed to the implementation instance that's created). Is this a good general approach for implementation of a factory method in C#?
You should rather take a step back and ask whether using a factory method at all is a good idea? In my opinion, it is not.
There are more than one issue with factory methods, and your example illustrates several:
You need to have a hard reference to the implementation (FooProvider in addition to IFooProvider), which is exactly the situation you are trying to avoid in the first place. Even if the rest of your code only consumes IFooProvider, your library is still tightly coupled to FooProvider. Some other developer may come by and start using FooProvider directly if he/she isn't aware of your factory method.
You only support implementations that have default constructors, since you are using Activator.CreateInstance. This prevents you from using nested dependencies.
Instead of trying to manually control dependencies, I would recommend that you take a look at Dependency Injection (DI). Whenever your code needs an IFooProvider, supply it with Constructor Injection.
Don't reinvent your own implementation of dependency injection, use an existing library like Spring.NET or the Microsoft Unity application block.
Injecting dependencies is a common programming problem that you shouldn't have to solve yourself. There are some nice lightweight libraries out there (I mentioned a couple above) that do the job well. They support both declarative and imperative models of defining dependencies and are quite good at what they do.
Technically this is fine, however most times when I see a factory it usually returns the same type interface, for instance something like IProvider rather than IFooProvider or IBarProvider which to me doesn't make sense. If you are going to have FooProvider and BarProvider then why have different interfaces for them. I would use one interface IProvider and have FooProvider and BarProvider implement that.
Regardless of the rightness or wrongness of using the factory method (as that is not what you asked about!), your implementation looks fine to me.
Something that may work for you better than hardcoding the type mapping is putting that info in a configuration file and loading it in your app.
For what it is worth I use this pattern all the time and have abstracted some of this sort of logic into a reusable assembly. It uses reflection, generics and attributes to locate and bind the concrete types at runtime. http://www.codeproject.com/KB/architecture/RuntimeTypeLoader.aspx
This helps to address Mark's concern because implementation types are not hardcoded, and further the implementation types are determined by the installation, not in project assembly references.
I'm still struggling a bit with OOP concepts and dependency injection so bear with me.
I have generated my Linq2Sql model with a User table and now I would like to be able to send a confirmation email to this user so I created a partial class file for my User object and I felt it was natural to add a SendConfirmationEmail() method to the User class. This method will use a MailService to send the actual email and I would like to use dependency injection to pass in the service so I created a constructor overload on the User object like this
public User(IMailService service) : this()
{
_service = service;
}
The SendConfirmationEmail method would look like this
public void SendConfirmationEmail()
{
_service.SendMail(params...);
}
I realize this is a kind of poor mans dependency injection and I hope to switch to a dependency injection framework later as I am getting more grips on this.
The problem for me is that I need to make a reference from my model dll to my service dll which does not seem right and because I am unsure of how nice my linq2sql generated entities plays with Dependency injection frameworks and OOP concepts (I think ninject looks most promising).
I was hoping someone with a bit more experience than me could tell I'm if I am going in the right direction with this. I know I can make it work but I would like to educate my self in doing it in the correct way in the same step.
I personally would change some things in your architecture:
I don't think that SendConfirmationEmail should be a method on your User object. But should be a method on another object with the user as a parameter. (this also better seperates your Dal from the other logic.
Second in this method use something like this:
Services.Get<IMailService>().SendMail(params ...);
You can implement Services as the folowin (just an example):
public class Services
{
protected static Dictionary<Type, object> services = new Dictionary<Type, object>();
private Services()
{
}
static Services()
{
// hard coded implementations...
services.Add(typeof(IMailService), new DefaultMailServiceImplementation());
}
public static T Get<T>() where T : class
{
Type requestedType = typeof(T);
return services[requestedType] as T;
}
}
By using a "Services"-class (or call it what you like) you add an additional layer between the IOC-framework and your code which makes it easy to change IOC-frameworks. Just change the implementation in the Get method to use one. You can also use a hardcoded temporary solution (until you use an IOC-framework) in the static constructor (like I did in the above example).
The problem with that approach is that much of the time the entity is going to come from the LINQ-to-SQL back-end, and so isn't going to use your constructor (LINQ-to-SQL creates objects in its own way; you cannot force LINQ-to-SQL to use your constructor) - so this would only be useful for the (few) objects you create yourself. Data-binding (etc) will also commonly use the parameterless constructor by default.
I wonder if this wouldn't work better as a utility method that accepts the service, or obtains the service itself via a factory / singleton.
I think you're ok doing this, but you might want to do two additional things to protect yourself from future cross-layer dependency problems:
Create an interface for your User
object. You should do this because
not doing so will mean that
everything that consumes this
business object will have to
reference the LINQ dlls
unnecessarily.
Move your dependency injection from
the constructor into a property.
You do this because constructor
injection tends to limit your
ability to dynamically create your
object. Doing this, though poses a
problem, since you would have to
implement a lot of null checking
code for _service. You can fix this
by creating an "empty"
implementation of IMailService and
make it the default value for
_service.