How do bind my interface to a concrete class in a different assembly?
I have the following projects in my solution:
Foo.Data
Foo.Domain
In Structure Map I add my two assembly names to the StructureMap.config file and a then using the PluginFamily and Pluggable attributes map my interfaces to my concrete class'.
How can accomplish the same thing with Ninject?
I'll make a couple of assumptions here.
You have an interface named IBar in your Foo.Domain project and you have a concrete class called BarClass in your Foo.Data project.
You in fact reference Foo.Domain project in your Foo.Data project because BarClass implements IBar.
The simplest thing to do with Ninject is to create a new class in Foo.Data that derives from Ninject's StandardModule:
internal class BarModule : StandardModule {
public override void Load() {
Bind<IBar>()
.To<BarClass>();
}
}
This class then establishes the binding for requests of IBar to the concrete class of BarClass. This is your XML equivalent.
The next step is to create the Ninject kernel (aka a "container") and provide this module (i.e. this configuration) to it. Where you do this depends greatly on what kind of an application you are creating. In very general terms, you will typically configure the kernel at the logical entry point or "start-up" section of your code. If it were a console or Windows desktop application, this would likely be one of the first things that the main() function does.
The code would like this:
var modules = new IModule[] {
new BarModule()
};
var kernel = new StandardKernel(modules);
At this point, when you do something like this:
var barObj = kernel.Get<IBar>()
The variable barObj references an instance of BarClass.
All said, I could very well not have a full understanding of all the nuances of your application -- e.g. assemblies are loaded dynamically, etc. Hope this is of some help anyway.
Related
Say I have an Interface like this in a project called "Interface":
public interface TestInterface
{
string Operation();
}
and class which implements it. This class is located in another project "Class":
public class TestClass : TestInterface
{
public TestClass() { }
public string Operation()
{
return "This is an Operation";
}
}
My client does something like this (which is again in a different project "Client"):
class Program
{
static void Main(string[] args)
{
TestInterface i = new TestClass();
i.Operation();
}
}
My question is related to this line:
TestInterface i = new TestClass();
By adding this line, I'm actually forced to add a references to both "Interface" as well as "Class" projects from my "Client" project. So why all this fuss? Can't I directly refer to the "Class" without keeping the "Interface" in between? Is there any way to access the methods via Interface only (without making a reference to the implementation Class)? Am I missing something here?
Is there any way to access the methods via Interface only
Yes, there is. You can dynamically load an assembly with TestClass without referencing it, create its instance via Activator.CreateInstance and cast it to interface type:
var assembly = Assembly.Load(...);
var typeFromAssembly = assembly.GetTypes()...;
var myInterfaceVar = (TestInterface)Activator.CreateInstance(typeFromAssembly);
...or... you may use one of existing DI-frameworks (e.g. MEF) and do the same thing more right way:
[Import]
private TestInterface myInterfaceField;
or:
var myInterfaceVar = compositionContainer.GetExportedValue<TestInterface>();
Depending of the way you prefer, you may ask more concrete question.
In that particular sample, there is no advantage.
But imagine a method:
public void Foo(ITestInterface handler)
{
handler.Operation();
}
Now, Foo operates only on the interface and it doesn't care what concrete class implements this interface. You could now call Foo with an instance of TestClass or with TestClass2, which could be defined in a different assembly.
you can achieve the behavior you have described via using IOC.
Unity is a dependency injection container which allows to create instances without manually creating instances.
For instance, if you were to register your class and interface to unity, you would directly use the interface;
TestInterface i = Container.Resolve<TestInterface>();
To make your code completely independent from implementation of TestInterface use Dependency Inversion. This could be achieved by some Dependency Injection framework.
E.g. with Unity you can configure implementation via xml
<register type="TestInterface"
mapTo="Foo.Bar.TestClass, Foo.Bar" />
And your code will depend only on Unity (no references to implementation):
TestInterface i = Container.Resolve<TestInterface>();
You have interface so that your app can have plug in's..
So basically you share your Interface dll to anyone who wants to make a plugin app for your app and then you can cast that new plugin class to the interface and invoke methods on it..
If you dont cast the class to the interface,how on earth are you going to make the plugin class work for your app..
I am having the following problem. I have a main project, and some extra projects that have similar functionality.
For example: I have an MVC website, then a class library project "A" with a "SettingsHelper". This just defines static wrappers for configuration settings so they can be used as propertys.
Then I have another class library project "B", which also contains a "SettingsHelper class".
How can I merge these SettingsHelpers in my main project, so I can use: SettingsHelper.Property from both modular extra projects.
I would like to be able to plug extra class libraries into one project.
Sounds pretty much like Dependency Injection. Normally you would expose SettingsHelper as an interface (your contract), and program against that. Then a DI container, such as Ninject, StructureMap, or Windsor would plug an implementation of that interface into the relevant parts of your code based on configuration.
This would allow you to code against a known contract and provide different libraries depending on the circumstances, the DI framework could then use that library to get the concrete implementation of the interface.
Would you need both instances at the same time?
Note that you cannot utilise the partial keyword across different assemblies, only within an assembly.
Update: based on your comment it sounds like you want to do something like Composition. Have a class that takes both classes from either library and combines them into one class that can be used by your application. Whether you then configure it to do something special or load the types when the libraries are present, it can all be encapsulated in this new class.
Update 2: alternatively, look into MEF:
http://msdn.microsoft.com/en-us/library/dd460648.aspx
That won't work. Partial classes cannot be divided over assemblies -- they don't exist in the CLR, only in the editor and the compiler. So they are compiled together into a single CLR class.
What you can do, is inherit one from the other. However, helpers tend to be static classes, so that won't work either.
The other alternative is not to write helper classes, but extension methods. You can extend classes in one assembly with methods defined in another assembly (or multiple other assemblies). See also http://msdn.microsoft.com/en-us/library/bb383977.aspx.
I would say that move both Helper classes in 3rd project and add reference of that project to both of your projects. So this new library will become shared datastructures and functionalities library.
Regards.
The specific pattern you are after is called a Facade Pattern. Unfortunately you are not going to get any help from the compiler getting this right. Essentially:
Create a new CombinedSettingsHelper class in your local assembly.
If the two SettingsHelper types are in the same namespace you will need to set up aliases for them (check the reference properties in the solution explorer, and MSDN documentation for this).
Implement the object so that it can access both SettingsHelper objects.
To clean up your facade you might try having a abstract method along the lines of abstract object GetSettingValue(string name);. Your facade could then inherit from the same base class and call these on its contained children. For example:
public abstract class SettingsHelperBase { public object GetSettingValue(string settingName); }
// Assembly1
public class SettingsHelper : SettingsHelperBase { }
// Assembly2
public class SettingsHelper : SettingsHelperBase { }
public class SettingsHelper : SettingsHelperBase
{
private List<SettingsHelperBase> _backends = new List<SettingsHelperBase>();
public readonly PropertiesImpl Properties;
public class PropertiesImpl
{
private SettingsHelper _settingsHelper;
public string Name
{
get
{
return (string)_settingsHelper.GetSettingValue("Name");
}
}
internal PropertiesImpl(SettingsHelper helper)
{
_settingsHelper = helper;
}
}
public SettingsHelper()
{
_backends.Add(asm1::MyNs.SettingsHelper);
_backends.Add(asm2::MyNs.SettingsHelper);
Properties = new PropertiesImpl(this);
}
protected override object GetSettingValue(string settingName)
{
foreach (var item in _backends)
{
var val = item.GetSettingValue(settingName);
if (val != null)
return val;
}
return null;
}
}
There is a way; Visual Studio allows the same code file to be included in more than one project.
When you do “Add”/”Existing Item” to can select a file that is in the different folder.
This is what some of the silver light support does so as to allow a “common class” that has some method that are only on the server and one methods that are only on the client.
(As to the question of “good design” you will have to decide that yourself, a lot of people don’t like having the same class compiled in different ways in different projects. Think if the mess you could get in with #if XXX, when XXX is only defined in one of the projects)
I am looking to see how Ioc/Di can simplify wiring the following classes I use often.
Consider a library that has an abstract notion of an Entity and an interface for a data access object:
public abstract class EntityWithTypedId<TId> : IEntityWithTypedId<TId>{...}
public interface IDao<T, TId> where T : IEntityWithTypedId<TId>
For the dao, I have one implementation for NHibernate as well as a fake dao I find useful for testing:
// has an NHib implementation
public class Dao<T, TId> : IDao<T, TId> where T : EntityWithTypedId<TId> {...}
public class DaoFakeBase<T> : IDao<T, int>, IDisposable where T : IEntityWithTypedId<int> {...}
I currently do the following to define an Entity and Dao type for a given project:
/// <summary>
/// <see cref="IEntityWithTypedId{IdT}"/> with an int for an id
/// </summary>
[Serializable]
public abstract class Entity : EntityWithTypedId<int>
{
}
public class Dao<T> : Dao<T, int> where T : Entity
{
protected Dao(ISessionFactory sessionFactory) : base(sessionFactory) { }
}
Can I use a DI tool to define the Entity instead? Can someone show me a code sample of how to do it if so?
Can you also lay out how I might tell my test assembly to use DaoFakes and production to use NHib.Dao
I have been looking at Windsor, mostly because NHibernate contrib projects use it, but am also interested in MEF, AutoFac and Ninject, in that order. I realize that MEF is not an IoC container in the sense that Windsor is. From what I can see with Windsor I would use Installer classes, maybe an EntityInstaller and a DaoInstaller, although I might be missing a FActory type of object here too.
Cheers,
Berryl
UPDATE # KeithS
Are you saying to change something like:
class MyViewModel(IDao<MyClass, int> dao) {...}
becomes something like
class MyViewModel(Func<IDao<MyClass, int>, obj> getDaoFunc) {
_dao = getDaoFunc(this);
}
In your example...
class MyViewModel(IDao<MyClass, int> dao) {...}
...IDao would get resolved at runtime based on a previous registration within your container. The syntax for a Prism/Unity implementation is below...
IUnityContainer.RegisterType<IDao..., DaoFakeBase...>();
The RegisterType takes place within IModule.Initialize() of a given module as defined in the UnityBootstrapper class.
protected override IModuleCatalog GetModuleCatalog()
{
ModuleCatalog catalog = new ModuleCatalog();
catalog.AddModule(typeof(project.Init));
return catalog;
}
You can also register a given type based on a lifetime manager; to behave as a Singleton...
IUnityContainer.RegisterType<IShellController, ShellController>(new ContainerControlledLifetimeManager());
...where the IShellController resolved instance will remain the same returned instance throughout the lifetime of the IUnityContainer.
UPDATE:
Using your code the registration would look like this...
public interface IDao<T, TId> where T : IEntityWithTypedId<TId>
{ }
public class Dao<T, TId> : IDao<T, TId> where T : EntityWithTypedId<TId>
{ }
public class TId
{ }
public abstract class EntityWithTypedId<TId> : IEntityWithTypedId<TId>
{ }
public interface IEntityWithTypedId<TId>
{ }
IUnityContainer.RegisterType<IEntityWithTypedId<TId>, EntityWithTypedId<TId>>();
IUnityContainer.RegisterType<IDao<IEntityWithTypedId<TId>, TId>, Dao<IEntityWithTypedId<TId>, TId>>();
IDao<IEntityWithTypedId<TId>, TId> dao = IUnityContainer.Resolve<IDao<IEntityWithTypedId<TId>, TId>>();
I would not use IoC to register the relationship between DAOs and their types (which is basically what you'd be doing). This will lead to you using the IoC container as a "service locator", a known anti-pattern where you pass the IoC container into objects that will use it to get the DAO they need.
I think the best way to simplify this from a consumption perspective would be to define a strategy pattern, using a factory class or method:
public Dao<T, TId> GetDaoFor<T, TId>(T objectInstance) where T:EntityWithTypedId<TId>
{
//Here, you could use a Dictionary, Linq with some reflection, etc.
}
This one method can be injected as a delegate into classes dependent upon DAOs. The difference is that classes that need a DAO are dependent on a method that can give it to them, which can be provided by the IoC container; they are NOT dependent on the container itself (which is the primary source of evil inherent in the "service locator" pattern). This reduces the number of things you'd have to change if you re-wrote how you got these DAOs.
EDIT: A bit off-topic, but I opened the door:
The service location pattern is generally to be avoided, because it results in code that relies on the service locator. For instance, the following is common in code where the IoC has been exposed at child levels:
private IDependency _dependency;
public IDependency MyDependency
{
get {
_dependency = _dependency ?? IoC.Resolve<IDependency>();
return _dependency;
}
}
While this seems like a nice pattern (dependencies are lazily initialized, consuming code doesn't need to know about dependencies of the child, and you always* get a reference), this code will ALWAYS require the IoC singleton to exist. You can change the IoC framework behind it, you can remove the third-party tool altogether and roll your own, but this class will always require something on which to statically call Resolve<IDependency>().
You also don't ALWAYS get a reference; you get a reference only if you properly registered IDependency with IoC. This produces two more weaknesses; 1) you don't know what the class will need without opening it up, and 2) if/when the call fails, it will fail deep in the bowels of the dependent class' inner workings. If you develop a new class, and plug it into IoC, it may pass integration, and even work in production for a while, until you start getting weird "object reference set to null" errors in really weird places in code, which are, trust me, a nightmare to debug.
Lastly, unit-testing service-locator-pattern code is more difficult, for the simple reason that you must mock the service locator as well as the dependency provided by the service locator. You can leave the production service locator in use, and simply register mocked classes as the dependencies, but that's not a unit test; the test relies on, and thus to some extent tests, that the integration of the class and its service locator works as expected. That's an integration test.
By contrast, dependency injection patterns free you from any dependency on how dependencies are resolved. The only requirement (in constructor-injection) is that they be around when the class is created. This has several advantages:
If not using an IoC framework, you have to know what the class will need to instantiate it.
If using an IoC framework, you get a runtime error when attempting to instantiate the dependent class, not sometime later when the object actually gets resolved.
When testing a dependent class, you can more easily mock the dependency, because the dependency does not have to be fed in via the service locator.
You can in most IoC frameworks still lazily initialize dependencies by providing a factory method instead of the actual dependency to the constructor. The above pattern then calls that delegate, which could come from anywhere, instead of a static named method which is satisfied by one and only one construct in the entire codebase.
I'm doing some internal domain-specific library development at the moment, and incidentally the stuff i'm trying to model mimicks "class" and "object" relations fairly well. So objects of my C# class MyClass should sort of act like a domain specific class for objects of my C# class MyObject who play the part of object or instance. Now I would like the code in MyObject to access methods of MyClass, which should not be accessible to other classes/code in the project. Any ideas how to enforce this, asside from documenting it at hoping my fellow developers will respect this.
I hope I made my question clear enough, otherwise let me know.
Best regards!
You could always split MyClass and MyObject up into another project, and define MyClass and/or MyObject as an internal class. That way it can only be accessed by other objects in that assembly.
See: http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx
The standard approach here is to declare the members internal and make sure MyClass and MyObject are part of the same assembly. That assembly should contain little else.
Additional: This is the tool that was designed for this purpose. Other languages have other means to fine-tune accessibility (C++: friend) but in .NET a simpler model was chosen.
And you don't have to take the 'nothing else' so strictly, the 2 classes could share an assembly with other related classes. you would then have to verify the no-access rule(s) manually inside that library.
I'd suggest a private nested class. That way, even if your fellow devs are writing code in the same namespace, they'll never be able to access the class.
Once the class declaration is fully enclosed within another class declaration, the class is considered nested and can only be accessed through the containing class.
Pehaps your MyObject should descend from MyClass and declare the methods in MyClas as protected.
If you don't want your consumers to invoke certain implementation specific methods you could try abstracting to interfaces or abstract base classes. That way the consumer will only 'see' the properties and methods you want them to see.
You do not have to use inheritance to provide shared functionality and you do not have to rely on member accesibility to prevent others from using methods you'd rather not expose.
For example:
public interface IDomainSpecific
{
void DoStuff();
}
public interface IDomainService
{
void HelpMeDoStuff();
}
public class DomainObject1 : IDomainSpecific
{
private readonly IDomainService _service;
public DomainObject1( IDomainService service )
{
_service = service;
}
public DoStuff()
{
// Do domain specific stuff here
// and use the service to help
_service.HelpMeDoStuff();
}
}
This uses classic constructor injection and works best when you already use dependency injection in your application, though it works perfectly well with factories as well.
The point is to keep responsibilities crystal clear. There's no chance of anybody invoking anything they shouldn't because the 'DomainObject' never knows what concrete type implements the shared service. The shared service is not exposed on the domain object either. The added bonus is testability and the possibility of swapping the service with another implementation without ever needing to touch the DomainObject.
my problem: Inside an application, all interfaces are declared inside an own dll(project "interfaces", for example).
Inside project interfaces, there are many class implementations, too.
Now I need one of this implemented classes inside another project and get a ring dependency because this project is also a reference in project interfaces.
So, what is the best way to get around this ring dependency? Could it be possible that this is a big mistake in the design of the application?
Schematic representation:
IBigInterface.cs (everything in one file):
interface ISomeInterfaceA
{
void SomeFunctionA(ClassB x); // ClassB from newProject.cs
void SomeFunctionB();
}
//
// etc.
//
class ClassA
{
//
// Code
//
}
newProject.cs (everything in one file):
class ClassB
{
//
// used in interfaces.dll
//
}
class ClassC
{
void SomeFunction(ClassA a) // ClassA from IBigInterface.cs
{
//
// do something
//
}
}
First thing that comes into my mind would be sth. like:
IBigInterface.cs:
interface ISomeInterfaceA
{
void SomeFunctionA(IInterfaceB x); // use interface instead of a class
void SomeFunctionB();
}
interface IInterfaceB
{
//
// declarations
//
}
class ClassA
{
//
// implementation
//
}
newProject.cs:
class ClassB : IInterfaceB // implementation of IInterfaceB
{
}
class ClassC
{
void SomeFunction(ClassA a)
{
//
// implementation
//
}
}
so that project newProject wouldn't be a reference in project interfaces anymore (although this means changes in the whole application).
P.S.: I inherited this application so the idea of implementing classes in an interface-project was not my idea :).
In General, I would create one file per class (so don't point to this :).
First, there's nothing wrong with combining concrete classes and the interfaces they implement into a single assembly (though it would be a bit strange to call the project "interfaces").
Having said that, circular references are usually a sign that you've over-modularized your code: the parts causing the circular reference belong together and they should be merged into a single assembly.
Other times, a circular reference is just a sign that a class is in the wrong layer; the class needs to be moved into another assembly altogether (usually out of a lower-level infrastructure assembly and into a higher-level assembly). For example, ClassC might really belong in another project that references the "interfaces" assembly.
That's exactly the reason why Java requires public definitions to be in their own files (but I think you get the concept here :)).
It's usually not good to mix pure interface and implementation (though there are cases where it could be useful), and it's definitely a troublemaker if you export those into DLLs.
A cyclic dependency means your projects are too coupled to be distinct. This is usually a symptom of bad design (big ball of mud-like). You should either work on removing that coupling or merge both projects together.
If you have a specific project that, as you say, contains all your interfaces, why not introduce another project that contains "helper classes" such as ClassA? Then your interface DLL and the projects depending on the interface DLL could use the classes.
I would try to factor out the classes and interfaces that are common to several projects into a "Common" assembly (or similar), which has no dependencies to the assemblies that reference it.
For example, a business entity such as Product does not have to know anything about how it is persisted to a database or fetched via a web service, but the service components that do things with Product, for example IProductsRepository, needs to know what a Product is. Thus the assembly (or namespace) where IProductsRepository is defined holds a reference to the assembly (or namespace) where Product lives, but not the other way around.