How do I registertype with the container where the type doesn't have NO PARAMETER constructor.
In fact my constructor accepts a string, and I normally pass in a string that represents a Path.
So when I do resolve it automatically creates the new type but passing in a string?
The version of the RegisterType method taking Type instances as parameters is used instead of the version with generic type parameters. The version with generic type parameters benefits from compile-time type checks.
You can use the RegisterInstance method to register open generic types, types with all their generic type parameters left unspecified, with non-ambiguous constructors. Unity generic parameter injection run time API configuration support for parameters and properties is provided by the GenericParameter class.
To create a parameterized constructor in C++, we can add parameters to a function like it can be added to any other function. When the body of the constructor is defined, the parameters are used to initialize the object. The syntax included having name_of_class, followed by an access specifier that contains member functions and member variables.
The constructors have same name as their class and, have no return type. There are two types of constructors parameterized constructors and no-arg constructors. A parameterized constructor accepts parameters with which you can initialize the instance variables.
It's simple. When you register the constructor, you just pass the value you want injected for the parameter. The container matches up your constructor based on the type of value (API) or name of parameter (XML).
In the API, you'd do:
container.RegisterType<MyType>(new InjectionConstructor("My string here")); That will select a constructor that takes a single string, and at resolve time will pass the string "My string here".
The equivalent XML (using the 2.0 config schema) would be:
<register type="MyType"> <constructor> <param name="whateverParameterNameIs" value="My string here" /> </constructor> </register>
You can also use the built in InjectionConstructor and ResolvedParameter where connectionString is the database connection string to be used.
// install a named string that holds the connection string to use container.RegisterInstance<string>("MyConnectionString", connectionString, new ContainerControlledLifetimeManager()); // register the class that will use the connection string container.RegisterType<MyNamespace.MyObjectContext, MyNamespace.MyObjectContext>(new InjectionConstructor(new ResolvedParameter<string>("MyConnectionString"))); var context = container.Resolve<MyNamespace.MyObjectContext>(); You could take it even one step further and have multiple named instances of MyObjectContext, each using their own connection string to different databases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With