I am trying to implement a simple WPF data analysis application using the MVVM design pattern, in which one can use several different methods to analyse some data (loaded from files).
In the first screen, the user should be able to choose the method he likes to employ. After he has done that, and loaded the data, the area previously occupied by the method selection screen should be replaced by the analysis results.
Currently, my MainWindowViewModel has a property "CurrentViewModel" of type object, that can be set to either the method selection viewmodel or on of the analysis results viewmodels, which are then rendered by using datatemplates.
The problem I am facing is, that I don't know how the different viewmodels should communicate.
The method selection screen needs a
list of available methods.
The main screen needs to know what method was
selected and choose the approriate
viewmodel to display the results.
The data loaded somehow needs to get into the class doing the actual work, and the results viewmodel needs to know about this to know where to get its data from.
Everything I can think of leaves the MainWindowViewModel to do all the negotiating between the different viewmodel and model classes.
How would I optimally design this?
For what it's worth, I helped implement a module for a similar Composite Application. So what follows is based on anecdotal experience,
To your first point, our application or "shell" needs an explicit enumeration of "available" methods. We can supply this any way we wish, either explicitly (via config) or implicitly (via reflection). As a preference, I favor the former as it is less "magical".
To your second point, in addition to an explicit enumeration our shell must maintain a map from choice to implementation. Again, this may be accomplished any number of ways, but typically our enumeration is a list of "Types", and when a type is selected we request an implementation of that type from a factory. The easiest way to implement this pattern is to leverage an Inversion of Control container, such as Castle Windsor, Unity, Ninject, etc. To be honest, I don't remember what we used internally.
For example, consider,
// a simple Plain Old C Object that describes business methods.
public class BusinessMethod
{
// user-friendly name
public string Name { get; set; }
// type that actually implements
public Type ImplementationType { get; set; }
}
// ... meanwhile, back on the ranch ...
public void OnBusinessMethodSelection ()
{
// 1. if selected
if (BusinessMethodList.SelectedItem != null)
{
// 2. retrieve selected item
BusinessMethod selected =
(BusinessMethod)(BusinessMethodList.SelectedItem);
// 3. request implementation of selected item from
// IoC container
object implementation =
_container.Resolve (selected.ImplementationType);
}
}
To your third point, we need a way for disparate parts to communicate. Unfortunately we cannot rely on design-time methods (ie Command and Data bindings), so we must implement our own Event Aggregation service. Basically a "singleton" (as in single instance not static class) that knows about subscribers and publishers, and preferably an implementation that offers strong typing of arguments. Fortunately for us, many a greater man have gone before us, and we may benefit from their experience. Check out Kent Boogaart's Event Hub.
Here is an example of how we would use an Event Aggregator
// an example of a strongly typed subject. notice how subject
// defines content. semanticly, when someone creates and publishes
// an instance of this subject, they are requesting someone show
// an analysis view based on data content,
public class AnalysisSubject
{
// subject content, in this case a data result from
// a business method
public object Data { get; set; }
}
public class MainWindow : ISubscriber<AnalysisSubject> ...
{
// use whatever implementation of an IoC container we like
// here i assume we abstract from implementation and use a
// custom interface IContainer that exposes functionality
// that we need
private readonly IContainer _container = null;
public class MainWindow ()
{
// we're teh r00tz! we create an instance of IoC
// container for use throughout application
IContainer _container = new CustomContainer ();
// our container exposes both parameterized and
// type-parameterized resolve methods
IEventHub events = _container.Resolve<IEventHub> ();
events.Subscribe<AnalysisSubject> (this);
}
#region ISubscriber<AnalysisSubject>
// part of strongly typed subscriptions is that we
// may now handle strongly typed publications! yay!
public void Receive (AnalysisSubject subject)
{
// 1. request to display analysis of data
Type analysisType = subject.Data.GetType ();
// 2. get view control based on payload type
//
// NOTE: implicit usage below is not consistent
// with previous invocations, here we are submitting
// a type of something we already have, and actually
// want back something that knows how to handle it.
// most IoC containers can provide this functionality
// through "facilities" add ons that accept a
// parameter\discriminator like below, and produce
// something in return.
Control control = (Control)(_container.Resolve (analysisType));
// [alternatively] if the above is too "magical" where
// IAnalysisFactory is an interface we define for this
// express purpose
//IAnalysisFactory factory = _container.Resolve<IAnalysisFactory> ();
//Control control = factory.GetAnalysisControlFor (analysisType);
// 3. assign subject data to control
Control.DataContext = subject.Data;
// 4. display control
}
#endregion
}
And an example of publication
public class SomeBusinessView
{
private readonly IEventHub _events = null;
// we cannot function without an event aggregator of
// some kind, so we declare our dependency as a contructor
// dependency
public SomeBusinessView (IEventHub events)
{
_events = events;
}
public void DoMyThang ()
{
// 1. do some business
MyBusinessData data = SomeBusinessFunction ();
// 2. publish complete event
AnalysisSubject subject = new AnalysisSubject () { Data = data, };
_events.Publish (subject);
}
}
Every View typically gets a viewmodel. If you are dealing with nested usercontrols inside one window, using multiple viewmodels (one per control) may be overkill.
If you have a viewmodel per control and are disconnected regarding communication between them then you can either have a common model that is universal to all the viewmodels OR have a global event provider that allows models to talk to eachother. (Something they all can reference for change notifications etc).
If you don't use a viewmodel per control then have the viewmodel bound to the main window in which all nested controls report to the main window which reports to the viewmodel for the main window.
Could the data source of the selection be bound to the types of ViewModels you have and the path possibly be the name of each (be it a string property for a formatted name or the Type name explicitly). On Selection you then have the relevant object that has been selected.
Possibly each of the ViewModels references a common provider which as you say performs the results analysis and the two different Views simply display the same data in different ways.
Related
I have RichBox binded to a List<String>ListName in the using of the window I add some item in this list, but after I close this window and I open it i still have the old added name, I know that the View model don't be disposed when I close window, but I use this on closing
public virtual void Cleanup()
{
this.MessengerInstance.Unregister(this);
}
but this will clean only the Messenger and let all my other items with values, I want to clear all resource in this ViewModel when I close the window
Update :
with Rudi answer I try on closing to do
SimpleIoc.Default.Unregister<ScanViewModel>();
SimpleIoc.Default.Register<ScanViewModel>();
and it work, but it seems not right to me to Unregister the VM and register it again !
You can just unregister an instance of the class than remove the entire class if you want.
Snippet from SimpleIoc.cs:
//
// Summary:
// Removes the instance corresponding to the given key from the cache. The class
// itself remains registered and can be used to create other instances.
//
// Parameters:
// key:
// The key corresponding to the instance that must be removed.
//
// Type parameters:
// TClass:
// The type of the instance to be removed.
public void Unregister<TClass>(string key) where TClass : class;
Do keep in mind to get a new instance of the class on every resolve from SimpleIoC we need to specify a unique key to it in GetInstance()
so in ViewModelLocator.cs keep a reference to the currentKey used and un-register it on the next attempt, something like:
private string _currentScanVMKey;
public ScanViewModel Scan
{
get {
if (!string.IsNullOrEmpty(_currentScanVMKey))
SimpleIoc.Default.Unregister(_currentScanVMKey);
_currentScanVMKey = Guid.NewGuid().ToString();
return ServiceLocator.Current.GetInstance<ScanViewModel>(_currentScanVMKey);
}
}
This way each time the VMLocator is queried for Scan a new VM is returned after unregistering the current VM. This approach would comply with the guidelines suggested by "Laurent Bugnion" Here and I'd take it he knows his own libraries pretty well and you're not going to go wrong doing it that way.
I remember MVVM Light's author state somewhere SimpleIoC was intended to get dev's familiar with IOC principles and let them explore it for themselves. It's great for simple project's, If you do want more and more control over your VM injections then I'd suggest looking at things like Unity in which your current situation would have been resolved pretty easily since you could just go
// _container is a UnityContainer
_container.RegisterType<ScanViewModel>(); // Defaults to new instance each time when resolved
_container.RegisterInstance<ScanViewModel>(); // Defaults to a singleton approach
You also get LifeTimeManagers and sorts that give even greater control. Yes Unity is an overhead compared to SimpleIoC, but it's what the technology can provide when needed than having to write code yourself.
I guess this would do it:
SimpleIoc.Default.Unregister<ViewModelName>();
edit: how about this
public ViewModelName MyViewModel
{
get
{
ViewModelName vm = ServiceLocator.Current.GetInstance<ViewModelName>();
SimpleIoc.Default.Unregister<ViewModelName>();
//or SimpleIoc.Default.Unregister<ViewModelName>(MyViewModel);
return vm;
}
}
What's the right way to get my viewmodel to trigger a custom lookup control to throw up a modal dialog that essentially represents that lookup viewmodel? The custom lookup control's data context is that of the parent record view model. The lookup control also has another DependencyProperty that has it bound to a lookupviewmodel property on the parent record view model and this represents a sub lookupviewmodel.
METHOD 1) I currrently use an event on the lookupviewmodel that the custom control knows to listen for.
METHOD 2) I tried throwing a validation exception within the setter of the property on the lookupviewmodel that the lookup control's text propery is bound too. Then I hooked the ErrorEvent in the custom lookup control. But it seems that if the user "corrects" the value from within the dialog while in this event, the original value sticks. And worse, even after I call Validation.ClearInvalid, another ErrorEvent still fires that somehow adds the error back. So everything works here in the sense that all the viewmodels have the correct data, it's just that it seems like the textbox is ignoring that the bound text property has changed on the underlying data source when inside an ErrorEvent. So it seems like I can't correct an error while inside the processing of that error?
Another sub issue within method 2 is that Validation.ClearInvalid doesn't remove the red error border. I had to manually clear the ErrorTemplate too. Is that right?
I'd like to find a way to use natural error handling within the control to get it to throw up the modal dialog.
This isn't what you use events for. Events exist to facilitate decoupling: the object raising the event shouldn't know or care what the object(s) listening to it are doing. You're expecting an event to be able to change the value of a property from inside the property's setter - or worse, your event handler is calling the very property setter that's raising the event that it's handling, which means that you have to do something pretty hackish to avoid a stack overflow.
Your description isn't very clear (you're describing both the problem you're having and the non-working solutions you're trying at the same time, which is confusing), but it sounds like what you're trying to do is something more like:
if (IsValid(value))
{
_Property = value;
}
else
{
_Property = GetValueFromDialog();
}
The problem is that you don't want to have code in your view model that throws up a dialog, since that creates a view model that can't be tested outside of your WPF application.
The answer in this case is to use dependency injection. Create an interface called IDialogService:
interface IDialogService
{
object GetValueFromDialog();
}
Now add this property to your view model:
public IDialogService DialogService { get; set; }
The above code becomes:
if (IsValid(value))
{
_Property = value;
}
else
{
_Property = DialogService.GetValueFromDialog();
}
Create a dialog service for use in your WPF application that actually throws up the dialog and gets the result. When you instantiate your view model in your application, do this:
MyViewModel vm = new MyViewModel { DialogService = new WpfDialogService(); }
Thus, in your application, the property setter will put up the dialog and get the result exactly as you expect it to.
For your unit tests, create a mock dialog that looks like this:
public class MockDialogService : IDialogService
{
private object Result;
public MockDialogService(object result)
{
Result = result;
}
public object GetValueFromDialog() { return Result; }
}
You can then write a test like:
MyViewModel vm = new MyViewModel { DialogService = MockDialogService(ExpectedResult) };
vm.Property = InvalidValue;
Assert.AreEqual(ExpectedResult, vm.Property);
The above is really more a sketch of a solution than a solution - depending on how your application uses dialogs, you may need a lot more features than what are sketched out here. If you take a look at MVVM frameworks you'll find that a lot of them implement dialog services of one kind or another.
You can use a framework like MVVMLight or Prism which allow you to pass payloads between different entities in totally decoupled ways. MVVMLight is very lightweight compared to Prism. It has a concept of Messanger which acts as a system wide event bus. Similarly you have EventAggregator in Prism.
I'm developing a WinForms application in C#. I have limited experience in GUI programming, and I am having to learn a great deal on the fly. That being said, here's what I am building.
See the general GUI look at the following link:
GUI http://img227.imageshack.us/img227/1084/program0.jpg
Now, I have done a lot of the work already, but in the very bad Autonomous design pattern. I did not know the project would ever reach a certain size, and, as such, it is time to do some major refactoring.
I have been studying a great deal about GUI design patterns, and the pattern I am wishing to implement is the Passive View (see http://martinfowler.com/eaaDev/PassiveScreen.html). I am looking for some help on how to bring this all together.
Background:
1) Depending on what the user clicks in the "TreeView", the "List" in the bottom left-hand corner will display a list of objects that can populate the "Editor" area. These objects might be a TextBox or a DataGridView. The user toggles the List to choose what he/she wants to see in the "Editor"
2) The model is essentially a folder with data and configuration files. There is an external program that runs on a given directory, creates output files/folders, etc. This program I am developing is designed to effectively manage/configure these objects in a user-friendly way
3) The problem with the way I have been doing things is that it is next to impossible to test, and hence the move to the MVP-esque Passive View design pattern
I am trying to make it so that the program works independently of the View. I have not been able to find any examples where a more complex, interactive view is used with the Passive View pattern.
Questions:
1) Do I need to implement one large interface/view for the entire "look" of the program, then implement sub-interfaces/sub-views for each of the TreeView, Editor, Logger, etc.? Or is there a better "structure" to doing this?
2) When it comes to "handing off" events from the View to the Presenter/Controller (whatever terminology you wish to use W.R.T. the Passive View design pattern), what is the way I should be doing this? Sometimes I have simple properties that need to be updated, and sometimes I need a whole series of steps to unfold.
I would love suggestions and advice on this topic. I have scoured the Internet, and I haven't found adequate examples to help me continue with this project.
Thanks in advance!
Daniel
Here is a simple example that demonstrates the concept of passive views using the MVP design pattern. Because we are using passive views the view has no knowledge of the presenter. The presenter will simply subscribe to events published by the view and act accordingly.
To start out we need to define a contract for our view. This is typically achieved using an interface, essentially, we want to have a very loose coupling with our view. We want the ability to switch to different views or event create mock views for unit testing.
Here is a contract that describes a simple view that will be used to display customer information
public interface ICustomerManagementView
{
void InitializeCustomers(ICustomer[] customers);
void DisplayCustomer(ICustomer customer);
event EventHandler<EventArgs<ICustomer>> SelectedCustomerChanged;
}
It exposes a single method InitializeCustomers that will be used to initialize our view with objects from our model.
We also have an event SelectedCustomerChanged that will be used by our presenter to receive notification that an action has occurred in the view.
Once we have our contract we can start to handle these interactions in our presenter.
public class CustomerManagementPresenter
{
private ICustomer _selectedCustomer;
private readonly ICustomerManagementView _managementView;
private readonly ICustomerRepository _customerRepository;
public CustomerManagementPresenter(ICustomerManagementView managementView, ICustomerRepository customerRepository)
{
_managementView = managementView;
_managementView.SelectedCustomerChanged += this.SelectedCustomerChanged;
_customerRepository = customerRepository;
_managementView.InitializeCustomers(_customerRepository.FetchCustomers());
}
private void SelectedCustomerChanged(object sender, EventArgs<ICustomer> args)
{
// Perform some logic here to update the view
if(_selectedCustomer != args.Value)
{
_selectedCustomer = args.Value;
_managementView.DisplayCustomer(_selectedCustomer);
}
}
}
In the presenter we can use another design pattern called dependency injection to provide access to our view and any model classes that we may need. In this example I have a CustomerRepository that is responsible for fetching customer details.
In the constructor we have two important lines of code, firstly we have subscribed to the SelectedCustomerChanged event in our view, it is here that we can perform associated actions. Secondly we have called InitilaizeCustomers with data from the repository.
At this point we haven't actually defined a concrete implementation for our view, all we need to do is create an object that implements ICustomerManagementView. For example in a Windows Forms application we can do the following
public partial class CustomerManagementView : Form, ICustomerManagementView
{
public CustomerManagementView()
{
this.InitializeComponents();
}
public void InitializeCustomers(ICustomer[] customers)
{
// Populate the tree view with customer details
}
public void DisplayCustomer(ICustomer customer)
{
// Display the customer...
}
// Event handler that responds to node selection
private void CustomerTreeViewAfterSelect(object sender, TreeViewEventArgs e)
{
var customer = e.Node.Tag as ICustomer;
if(customer != null)
{
this.OnSelectedCustomerChanged(new EventArgs<ICustomer>(customer));
}
}
// Protected method so that we can raise our event
protected virtual void OnSelectedCustomerChanged(EventArgs<ICustomer> args)
{
var eventHandler = this.SelectedCustomerChanged;
if(eventHandler != null)
{
eventHandler.Invoke(this, args);
}
}
// Our view will raise an event each time the selected customer changes
public event EventHandler<EventArgs<ICustomer>> SelectedCustomerChanged;
}
If we wanted to test our presentation logic we could mock our view and perform some assertions.
EDIT : Included custom event args
public class EventArgs<T> : EventArgs
{
private readonly T _value;
public EventArgs(T value)
{
_value = value;
}
public T Value
{
get { return _value; }
}
}
I would break them down into separate views with their own presents, and use a "controlling" presenter / view to manage message delegation between them all. Not only will this aid testability but it'll keep your controls fulfilling SRP, too.
So in your case you might have an IFormManager which your main window will implement, and then an IFileManager, ILoggerWindow etc. etc.
Although it might be a bit overkill to use, I would suggest that you have a look at Smart Client Software Factory (from the Microsoft Patterns and Practices team) - it's not being actively developed any more, but it has a good implementation of MVP and does this sort of view composition stuff quite well, so might give you some good ideas.
I am developing a project that calculates various factors for a configuration of components.
The configuration is set/changed by the user at runtime. I have a Component base class and all configuration items are derived from it.
The information for each component is retrieved from data storage as and when it is required.
So that the storage medium can change I have written a DataInterface class to act as an intermediary.
Currently the storage medium is an Access Database. The DataInterface class thus opens the database and creates query strings to extract the relevant data. The query string will be different for each component.
The problem I have is designing how the call to GetData is made between the component class and the DataInterface class. My solutions have evolved as follows:
1) DataInterface has a public method GetXXXXData() for each component type. (where XXX is component type).
Sensor sensor = new Sensor();
sensor.Data = DataInterface.GetSensorData();
2) DataInterface has a public method GetData(componentType) and switches inside on component type.
Sensor sensor = new Sensor();
sensor.Data = DataInterface.GetData(ComponentType.Sensor);
3) Abstract component base class has virtual method GetData() which is overidden by each derived class. GetData() makes use of the DataInterface class to extract data.
Sensor sensor = new Sensor();
sensor.GetData();
//populates Data field internally. Could be called in constructor
For me solution 3 appears to be the most OOD way of doing things. The problem I still have however is that the DataInterface still needs to switch on the type of the caller to determine which query string to use.
I could put this information in each component object but then this couples the components to the storage medium chosen. Not good. Also, the component should not care how the data is stored. It should just call its GetData method and get data back.
Hopefully, that makes sense. What im looking for is a way to implement the above functionality that does not depend on using a switch on type.
I'm still learning how to design architecture so any comments on improvement welcome.
TIA
Actually, solution #3 is the worst because it gives the Sensor class artificial responsibilities. The other two solutions are better in that they encapsulate the data access responsibilities into different classes.
I would suggest the following interfaces and classes.
interface IComponentDataReader
{
object GetData();
}
abstract class AbstractComponent
{
private IComponentDataReader dataReader;
public AbstractComponent(IComponentDataReader dataReader)
{
this.dataReader = dataReader;
}
protected object GetData()
{
return dataReader.GetData();
}
}
class Sensor : AbstractComponent
{
public Sensor(IComponentDataReader dataReader)
: base(dataReader)
{
}
public void DoSomethingThatRequiresData()
{
object data = GetData();
// do something
}
}
class SensorDataReader : IComponentDataReader
{
public object GetData()
{
// read your data
return data;
}
}
class MyApplication
{
public static void Main(string[] args)
{
Sensor sensor = new Sensor(new SensorDataReader());
sensor.DoSomethingThatRequiresData();
}
}
I hope this makes sense. Basically, for good OOD, if you can keep your classes to do only one thing (Single Responsibility Principle) and know only about itself, you will be fine. You must be asking why there is an IComponentDataReader passed to SensorComponent if it should only know about itself. In this case, consider that this is provided to SensorComponent (Dependency Injection) instead of it requesting for it (which would be looking outside its own responsibilities).
First, I agree with the idea of each component object, in it's constructor being responsible for asking for its configuration. In fact, perhaps that's pushed up into the base class constructor. We end up with
DataInterface.GetData( getMyType() );
kind of a call.
Then, you main question, how can we implement GetData( type)?
In effect you want a mapping from a type to a query string, and you don't want to be changing code as new components are added. So how about providing some data-driven approach. A simple external configuration proving that mapping. Then it's just a config change to add more components.
If i understand you right you make it a little too complicated:
Define an iterface with the getData() method (and a few connect, disconnect methods and maybe some Exceptions would also be a good Idea).
Derive a seperate class for every data provider / different storage type bassed on that interface like "AcdcessStorage", "MySQLStorage", "WhateverStroage" ...
Now you can quickly exchange one data storage implementation another, have different connection methods/query strings for each implementation and you can use multiple storages at the same time and iterate through them by a static interface method tha hass acces to all storages and keeps them in a list.
No need for any switches.
I've recently started using an IoC container for the first time, but I'm not educated on the best practices for using it. More specificaly I'm using Unity in a C# .NET project, and I started using it because it came with Prism.
I use the container to resolve the "top level" objects, and they get the correct objects injected based on the container. However, I can't see the best practice clearly when I have an object with children and children's children, and I need some data from the IoC container all the way down, but not in between. How you'd typically organize the use of IoC container?
Initially I'd think that you'd pass the container everywhere it is needed instead of extracting the needed data from the container on top-level and passing this data on. But then again I get problems when I reach objects which take other specific data in addition to the injected interfaces, and I'd prefer not to inject these through properties or init-methods after resolving the object.
I hope this was clear enough, but let's look at a fictional (and slightly stupid..) example.
class Employee
{
private ICommands _commands;
priate List<Customer> _customers = new List<Customer>();
public Employee(ICommands commands)
{
_commands = commands;
}
public void AddCustomer(string customerName)
{
var customer = new Customer(customerName, _commands);
_customers.Add(customer);
}
}
class Customer
{
private string _name;
private ICommands _commands;
priate List<Case> _cases = new List<Case>();
public Customer(string, name, ICommands commands)
{
_name = name;
_commands = commands;
}
public void AddCase()
{
var case = new Case(_commands);
_cases.Add(case);
}
}
class Case {
private ICommands _commands;
public Customer(ICommands commands)
{
_commands = commands;
}
public void TriggerCommands()
{
_command.TriggerSomething();
}
}
So, this example doesn't really make much sense, but the essence is the same of what I need to do. I have some application commands I pass down the line through my ViewModel classes, because some of them need to be able to trigger commands to display something. I also have common storage, etc. which may be needed for some classes but currently are passed through and stored in middle classes. With only commands it's no big deal if you store commands or container, but would one in a typical IoC-usage pass the IoC container instead, and use this for resolving objects down the line? And what about specific data like the customer name? You can't just pass this in on the Resolve(), so you need to inject that afterwards?
Sorry - this was as short as I was able to make it. Won't require answers of the same length ;-) .. Just; what's the best practice of doing stuff like this with IoC containers?
I'm not quite sure that I understand your question. But I don't think you should be passing the container around at all. It's much easier to just create a wrapper class for the container. For example:
public class IoCContainer
{
private static ContainerType = null;
public static ContainerType Instance
{
get
{
if (_container == null)
{
string configFileName = ConfigurationManager.AppSettings[ConfigFileAppSettingName];
_container = new WindsorContainer(new XmlInterpreter(configFileName));
}
return _container;
}
}
}
Now you call this everywhere in your code.
IoCContainer.Instance.Resolve<IAwesomeService>();
Does this help you?
I'm not sure if this answers your question, but I would say that a good way to act on an application using the Unity container (also applicable to other IoC engines I think) is:
Design your classes so that all the
required dependencies are specified
in the constructor. This way you
don't need to explicitly deal with
Unity unless you need to create new
objects.
If you need to create new objects
within your classes, pass the Unity
container itself in the constructor
as well (as a reference to
IUnityContainer), and create all new
object instances by using the Resolve
method. Even for objects that are not
registered and have not dependencies,
the container will give you a proper
instance, and later you can decide to register types that were not previously registered, without changing the client code.
As for passing explicit values to resolved objects, you can specify concrete injection members when you register types (see the InjectionMembers parameter in the RegisterType class).
It seems that you need to declare factories for your entities. Resolve factories via constructor injection and pass data values via Create method. All other dependencies must be resolved via factory's constructor.
See this answer.
I'd define a static class IoC, that can be initialized with a particular container and implement methods like Resolve, Resolve(...), which in turn delegate the actual work to the container instance (you'll store this instance in a field or property). This way you don't have to pass anything around, just use
IoC.Resolve<SomeType>();
anywhere in your code.
Regarding the specific data: some containers will take a parameter and resolve depending on this parameter (Autofac has this kind of feature). Or you can always create a factory class that will have a method that accepts a set of parameters (like customer name) and returns a corresponding object instance.