var container = new UnityContainer(); container.RegisterType<IDataContext, SqlDataContext>();In the 'high level' code you don't have to know the concrete type that implements the data access but just the contract: IDataContext. Unity will resolve the implementation you have registered at runtime:
var dataAccess = container.Resolve<IDataContext>();
Pretty easy so far but what if you want to pass a parameter to the constructor of your IDataContext implementation, e.g. a connection string? Just pass the value you want to be injected as a parameter when registering the type:
container.RegisterType<IDataContext, SqlDataContext>( new InjectionConstructor(connectionString));Unity will pass the value you have defined here to a matching constructor of SqlDataContext when you will request an instance of it.
No comments:
Post a Comment