Binding private and internal members using the CompositionContainer
By default, the CompositionContainer will not bind to private and internal members. For example, given the following fictional class:
public class ConnectionFactory
{
[Import("ConnectionString")]
private string _ConnectionString;
public string ConnectionString
{
get { return _ConnectionString; }
}
[...]
}
Running the following code:
CompositionContainer container = new CompositionContainer();
container.AddValue("ConnectionString", "Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
ConnectionFactory factory = new ConnectionFactory();
container.AddComponent(factory);
container.Bind();
Console.WriteLine("ConnectionString: " + factory.ConnectionString);
Outputs the following:
ConnectionString:
As you can see, the value we added explicitly to the container was never bound to the ConnectionFactory._ConnectionString field.
To allow private and internals members to be injected, simply apply the AllowNonPublicCompositionAttribute to the assembly that contains the imports. For example:
[assembly: AllowNonPublicComposition]
Rerunning the above code after applying the attribute, outputs the following:
ConnectionString: Data Source=.;Initial Catalog=Northwind;Integrated Security=True
Note: This applies to both private and internal imports and exports.