I have an ASP.Net MVC application and I am using StructureMap within MVC to glue the whole application together. There are some model classes that have heavyweight dependencies that are not used in all public methods, so I pass in an IContainer to the model constructor and use that to create the heavyweight dependencies on demand.
My question is where does the IContainer come from that is injected? Is it a reference to the one held centrally by MVC (it's logical parent) or is it a brand new one created and configured solely for this class?
The container injected into a constructor that has an IContainer parameter is the same container that is creating the instance of the class with the constructor.
Jeremy Miller has expressed this behaviour as "IContainer is injected into itself by default" in his blog post on NHibernate with StructureMap.
Couldn't you go with a factory model for creating those dependencies when needed in order to reduce your coupling to the container?
You could make your model take a Func as parameter and use SM's ability to autoinject those:
public class MyModel
{
Func<IHeavyDep> _heavyFactory;
public MyModel(Func<IHeavyDep> dependency)
{
_heavyFactory = dependency;
}
public void UsesHeavy()
{
var heavy = _heavyFactory();
heavy.DoMyStuff();
}
}
Related
I'm trying to implement passive attributes in an ASP.NET Web API. The filter I'm implementing has a dependency on a repository, which itself has a dependency on a custom DbContext.
In the post it says that you can resolve the component with a DI container, but also that the code should be invoked from Application_Start.
I'm not sure how to implement this, while taking advantage of the DI container's lifetime management capabilities (so that a new DbContext will be used per request). Would injecting an abstract factory be a good solution for this? or is there something simpler that I'm missing.
You can resolve this issue by sliding a Decoraptor in between the Filter and the Repository.
Not knowing a lot about your code, you should be able to define a Decoraptorepository using an Abstract Factory:
public class Decoraptorepository : IRepository
{
private readonly IFactory<IRepository> factory;
public Decoraptorepository(IFactory<IRepository> factory)
{
this.factory = factory;
}
// Just guessing IRepository's member(s) here...
public void Save(Foo foo)
{
this.factory.Create().Save(foo);
}
// other members...
}
This enables your Filter to stay a Singleton, while the actual Repository is being created in a Transient manner.
If you need to dispose of objects too, please refer to the follow-up article on how to decommission Transient objects from within a Decoraptor.
I made a small test function for creating an Entity Framework Code-First DbContext instance directly connected to a SQL CE 4.0 file but I really don't like the global state approach. Isn't there a better way to do this, without using DbDatabase static properties?
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Database;
using System.Data.SqlServerCe;
public class SqlCeDb
{
public static T Instance<T>() where T: DbContext, new()
{
DbDatabase.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
DbDatabase.SetInitializer<T>(new DropCreateDatabaseAlways<T>());
return new T();
}
}
Dependency Injection is what a lot of people are doing. You write a class that has a dependency on DbContext (i.e. it's a constructor argument or a property decorated as a dependency), and the IoC (Inversion of Control) container will give you an instance of it when the class is created. Every IoC container I've worked with has a way of registering a single instance (instead of creating a new instance every time).
Popular IoC Containers:
StructureMap
Unity
Ninject
There are others, but these are the ones I see used most often.
I have 3 project files
webui - controllers and views
framework - service layer and repos
tests- unit tests
So how I see it is that my controllers will only talk to my service layer(that contains my business logic). The service layer will talk to the repos and get database data.
My repo will just talk do the database and return data.
Now if I want to unit test this I need to have fake service layers and fake repositories.
this way I can test the controllers in isolation and the service layers in isolation.
So where do I put my ninject code in my framework class library so that I can use it with my service layer?
Edit
Steven are you saying I should be doing something like this
//setup ninject in global aspx with mvc extension
// now bind the stuff
private class SportsStoreServices : NinjectModule
{
public override void Load()
{
Bind<IAdminService>().To<AdminService>();
Bind<IAdminRepo>().To<AdminRepo>();
}
}
// controller
public class AccountController : Controller
{
//
// GET: /Account/
private IAdminService adminService;
public AccountController(IAdminService adminService)
{
this.adminService = adminService;
}
public ActionResult Login()
{
var getAllAdmins = adminService.GetAllAdmins();
return View();
}
}
// Service Layer
public class AdminService : IAdminService
{
private IAdminRepo adminRepo;
public AdminService(IAdminRepo adminRepo)
{
this.adminRepo = adminRepo;
}
public List<Admins> GetAllAdmins()
{
return adminRepo.GetAllAdmins();
}
}
//Repo
public class AdminRepo : IAdminRepo
{
public List<Admins> GetAllAdmins()
{
// some query to get all admins
}
}
When you follow the Dependency Injection pattern correctly (and completely) the only place you need to reference your IoC container is in your application root (in your case your web project). For MVC you would typically have a ControllerFactory that knows how to create new controllers using your particular IoC framework. Your controllers will be designed around constructor injection so your IoC framework is able to automatically inject all the dependencies. You will typically use constructor injection throughout the whole project. This allows you to let the rest of your code stay ignorant of the choosen IoC implementation.
For unit tests you would normally use constructor injection to manually inject the dependencies. This saves you from having to configure your IoC framework for your unit tests. Using an IoC library in your test project is painful, because you often want different dependencies to be returned per test case and testing frameworks often run your tests in parallel. So best is to not use any IoC framework in your tests, but call the constructor of a type under test yourself.
The trick for unit tests with DI is to keep your unit tests maintainable. You can do this for instance, by extracting the creation of a type under test into a factory method. This allows you to call such a constructor just in one place in your code. When the constructor changes, you would will have to change your test code in one place. I learned a lot about writing maintainable unit tests by the book The Art of Unit Testing. I can recommend it.
At project the DI should be in the place where the object composition can Happen.. For instance in WCF service Project we can do it using IInstanceProvider,IN asp.net Global.asax .
Ground rule:Make sure the DI is the application start up point
I have MVVM Project and I want to share one object( singleton ) from the model between several viewmodel what is the good practice to do that?
Thank you for the help
If the object is needed and does not provide value without it force the interface within the object via Constructor Injection; do not push a concrete type via injection always make use of an interface.
Since you are not making use of an IoC container such as Unity, you will need to create your singleton instance at the startup of your application and then make sure that the given instance is passed in via the given ViewModels constructor as needed.
A better approach would be pushing the singleton instance to a service which can provide the needed behavior and then disregard pushing the singleton into the Model. This would be a more MVVM purist approach and will separate concerns across your Models/ViewModels.
EDIT:
If you were making use of Unity you would define a Lifetime Manager at the time of registration.
// Register a type to have a singleton lifetime without mapping the type
// Uses the container only to implement singleton behavior
myContainer.RegisterType<MySingletonObject>(new ContainerControlledLifetimeManager());
// Following code will return a singleton instance of MySingletonObject
// Container will take over lifetime management of the object
myContainer.Resolve<MySingletonObject>();
Once you do this any attempt to resolve MySingletonObject via the IUnityContainer would resolve to the same instance providing the singleton behavior you so desire across the application. ViewModels themselves should not need to have the same instance returned. The data it needs should be abstracted away via a service as referenced earlier which could potentially behave like a singleton and provide a stateful implementation if needed but the ViewModel should not need to be a singleton. If you find yourself making either a Model or ViewModel a singleton; take a step back and analyze your design.
If you have control over all viewmodels then an easy approach (that I've used personally) is to just put a static variable on the base class of all viewmodels and make that accessible to all inheritors (either protected or even public if its useful outside of the viewmodels).
It's good practice anyway to have a common base class for your viewmodels since it allows you to implement property notification in one place (and other common functionality, like messaging etc.) instead of replicating it in all viewmodels.
Something like this is what I've used in my projects:
public class MyViewModelBase : INotifyPropertyChanged
{
private static MySharedSingleton _sharedObj;
static MyViewModelBase()
{
_sharedObj = new MySharedSingleton(/* initialize it here if needed */);
}
// or public
protected MySharedSingleton SharedObject { get { return _sharedObj; } }
// INotifyPropertyChanged stuff
// ...
}
public class SomeViewModel : MyViewModelBase
{
void SomeMethod()
{
SharedObject.DoStuff();
}
}
If the construction of the shared singleton object is heavy, you can of course use any of the standard techniques for lazy instantiation of it.
I would suggest that you inject the dependency into each view model (either constructor or property injection for example), and always work against abstractions in your view models, so that your dependency can easily be mocked or replaced as required. You then just need to ensure that each view model uses the same instance of your type - if you are using an IoC container, you can register a shared instance of your type easily.
I use a separate class for my global singleton with a model. This relieves me of agonizing over how to inject this model into view models and other models. E.g.
The singleton:
public class ApplicationModel
{
public string LoggedOnUser { get; set; }
// Etc.
private ApplicationModel() {
// Set things up.
}
private static ApplicationModel _active;
public static ApplicationModel Current {
get {
if (_active == null) {
_active = new ApplicationModel();
}
return _active;
}
}
}
The view model that needs to hold no reference to the singleton:
public class SomeViewModel
{
private string _user;
public SomeViewModel() {
_user = ApplicationModel.Current.LoggedOnUser;
}
}
I'm using constructor dependency injection in my WPF application and I keep running into the following pattern, so would like to get other people's opinion on it and hear about alternative solutions.
The goal is to wire up a hierarchy of ViewModels to a similar hierarchy of Models, so that the responsibility for presenting the information in each model lies with its own ViewModel implementation. (The pattern also crops up under other circumstances but MVVM should make for a good example.)
Here's a simplified example. Given that I have a model that has a collection of further models:
public interface IPerson
{
IEnumerable<IAddress> Addresses { get; }
}
public interface IAddress
{
}
I would like to mirror this hierarchy in the ViewModels so that I can bind a ListBox (or whatever) to a collection in the Person ViewModel:
public interface IPersonViewModel
{
ObservableCollection<IAddressViewModel> Addresses { get; }
void Initialize();
}
public interface IAddressViewModel
{
}
The child ViewModel needs to present the information from the child Model, so it's injected via the constructor:
public class AddressViewModel : IAddressViewModel
{
private readonly IAddress _address;
public AddressViewModel(IAddress address)
{
_address = address;
}
}
The question is, what is the best way to supply the child Model to the corresponding child ViewModel?
The example is trivial, but in a typical real case the ViewModels have more dependencies - each of which has its own dependencies (and so on). I'm using Unity 1.2 (although I think the question is relevant across the other IoC containers), and I am using Caliburn's view strategies to automatically find and wire up the appropriate View to a ViewModel.
Here is my current solution:
The parent ViewModel needs to create a child ViewModel for each child Model, so it has a factory method added to its constructor which it uses during initialization:
public class PersonViewModel : IPersonViewModel
{
private readonly Func<IAddress, IAddressViewModel> _addressViewModelFactory;
private readonly IPerson _person;
public PersonViewModel(IPerson person,
Func<IAddress, IAddressViewModel> addressViewModelFactory)
{
_addressViewModelFactory = addressViewModelFactory;
_person = person;
Addresses = new ObservableCollection<IAddressViewModel>();
}
public ObservableCollection<IAddressViewModel> Addresses { get; private set; }
public void Initialize()
{
foreach (IAddress address in _person.Addresses)
Addresses.Add(_addressViewModelFactory(address));
}
}
A factory method that satisfies the Func<IAddress, IAddressViewModel> interface is registered with the main UnityContainer. The factory method uses a child container to register the IAddress dependency that is required by the ViewModel and then resolves the child ViewModel:
public class Factory
{
private readonly IUnityContainer _container;
public Factory(IUnityContainer container)
{
_container = container;
}
public void RegisterStuff()
{
_container.RegisterInstance<Func<IAddress, IAddressViewModel>>(CreateAddressViewModel);
}
private IAddressViewModel CreateAddressViewModel(IAddress model)
{
IUnityContainer childContainer = _container.CreateChildContainer();
childContainer.RegisterInstance(model);
return childContainer.Resolve<IAddressViewModel>();
}
}
Now, when the PersonViewModel is initialized, it loops through each Address in the Model and calls CreateAddressViewModel() (which was injected via the Func<IAddress, IAddressViewModel> argument). CreateAddressViewModel() creates a temporary child container and registers the IAddress model so that when it resolves the IAddressViewModel from the child container the AddressViewModel gets the correct instance injected via its constructor.
This seems to be a good solution to me as the dependencies of the ViewModels are very clear and they are easily testable and unaware of the IoC container. On the other hand, performance is OK but not great as a lot of temporary child containers can be created. Also I end up with a lot of very similar factory methods.
Is this the best way to inject the child Models into the child ViewModels with Unity?
Is there a better (or faster) way to do it in other IoC containers, e.g. Autofac?
How would this problem be tackled with MEF, given that it is not a traditional IoC container but is still used to compose objects?
Depending on the container can you not specify a parameter (named or otherwise) in your factory's CreateAddressViewModel method?
container.Resolve<IAddressViewModel>(new NamedParameterOverloads() { { "Address", model } };
Depending on the container your factory may have to know the name of the parameter (TinyIoC and Castle afaik), or it may had to be last in the list of constructor dependencies (YMMV depending on containers), which isn't great, but it saves creating a lot of child containers in quick succession, and the GC thrashing that will follow, and you still get DI for all your other dependencies.
Of course this falls down if your VM also has a dependency that requires the same IAddress, in that case a child container is probably the way to go unless you want the VM to have knowledge of the container.
Update:
If you're using a subcontainer of a container that uses "last register wins" (which I think Unity does), then you could pass the same child container into your Factory each time, and have your factory simply register the new IAddress - that way you wouldn't be creating a new UnityContainer instance on the heap for each iteration and it should cut down on garbage collections if you're creating lots of items.
The ViewModel sample application of the WPF Application Framework (WAF) shows how you could bring the Model and the ViewModel together. The sample uses MEF as Dependency Injection Framework.