开发者

Unity - resolving without resolve()

I would like to just markup a property with an attribute [DoInjection] and have unity do the injection. I don't want to have to use prop = Unity.Resolve(type). Thats a pain and messy. Does unity provide attributes to do this or do I have to build my own?

Edit: register in App.Main

ISessionFactory sf = new SessionFactory();
            container.RegisterType<IRepository, CustomerRepository>(new InjectionConstructor(sf.CurrentUoW));
            container.RegisterInstance<IUnitOfWork>(sf.CurrentUoW);

Using [Dependancy] on IUnitOfWork propery in ClassX other class but it's always null. Do I need to build ClassX instance using Unity to get this to work? It looks like I do have to. I开发者_C百科 don't like that.


Unity has a DependencyAttribute you can use for this:

public class MyObject
{
  private SomeOtherObject _dependentObject;

  [Dependency]
  public SomeOtherObject DependentObject 
  {
    get { return _dependentObject; }
    set { _dependentObject = value; }
  }
}

http://msdn.microsoft.com/en-us/library/ff650198.aspx

Based on your question, it sounds like you might be trying to use Unity in the wrong spot and your design sense was telling you it didn't feel right. You should only see Unity where you bootstrap your application. That's your Main method in a console app or Global.asax in a web or wcf app. The idea is to keep relying on dependencies all the way up the chain until you get to where you bootstrap and resolve just that one top level object using your IoC container. In a console app, I do this:

class Program
{
    static void Main(string[] args)
    {
        using (var container = new UnityContainer())
        {
            container
                .AddExtension(new ConfigureForConsole(args))
                .Resolve<MyApplication>()
                .Execute();
        }
    }
}

http://www.agileatwork.com/console-application-with-ioc/

In this case, MyApplication is my top level object (it doesn't need to be an interface here). The ConfigureForConsole is just a one-off custom container extension that has all the RegisterType lines in there. Alternatively you could initialize the container from App.Config here. The idea though is that your Main method has almost nothing in it. Another benefit of this approach is that it makes your code more portable. I find that console apps usually turn into windows services and keeping things clean here makes that transition pretty painless.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜