views:

28

answers:

2

Hi there,

Can anyone help?

How do i registertype with the container where the type doesn't have NO PARAMETER constructor.

Infact 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?

Thanks in advance

A: 

I don't know specifically about Unity, but the general way to solve this is to use a factory type wherever you would require your type directly. That is, instead of this:

class NeedsAFoo
{
    public NeedsAFoo(Foo foo) { ... }
}

class Foo
{
    public Foo(string something) { ... }
}

you adapt NeedsAFoo to accept a IFooFactory instead of a Foo directly:

class NeedsAFoo
{
    public NeedsAFoo(IFooFactory fooFactory) { ... }
}

interface IFooFactory
{
    Foo Create(string something) { ... }
}

This of course only shifts the problem away from NeedsAFoo to IFooFactory -- the good news, however, is that DI containers usually have special support for factories. (And even if they didn't, you now have one central place where the new-ing up Foo objects is encapsulated, namely in the implementation of an IFooFactory.)

Hopefully, someone more knowledgeable about Unity will provide the details. As a start, maybe some other posts here on SO will help you along, e.g. this one.

stakx
thanks for the reply. The problem is the parameter on the constructor isn't a Type that needs resolving... its a basic string that i need to pass something into..... So i don't want unity to resolve the parameter (it can't - its a string) but want to force passing in a parameter on my RegisterType method.
Martin
@Martin, I assumed you were talking about a non-auto-injectable parameter whose value can't be determined early -- if, however, you always pass the same path string to your constructor, then I agree that there'll likely be simpler solutions than the one pointed out above.
stakx
+1  A: 

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>
Chris Tavares
Thank, just what i needed.
Martin