RSS

Tag Archives: dependency injection

Dependency Injection in Web API With Unity IoC

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var container = new UnityContainer();
        container.RegisterType<IProductRepository, ProductRepository>();
        config.DependencyResolver = new UnityResolver(container);

        // Other Web API configuration not shown.
    }
}

Global.asax.cs

protected void Application_Start()
{
    // Some code here...

    WebApiConfig.Register(GlobalConfiguration.Configuration);

    // Some code here...
}

Version attow: Unity 3, Web API 2

 
Leave a comment

Posted by on November 18, 2014 in General

 

Tags: , , ,

Unity Dependency Injection in ASP.NET MVC Authorize Attribute

Often times, we need custom Authorize attribute used in ASP.NET MVC to customized authorization using our own authorize / authentication service. And with that, we need to inject dependency into the attribute.

In C#, only certain type can be passed into an attribute. To get dependency in an attribute: DependencyResolver.Current.GetService()

public class MyAuthorizationAttribute : AuthorizeAttribute
{
    public IMyAuthService myAuthService { get; set; }

    public PartDAuthorizationAttribute()
    {
        myAuthService = DependencyResolver.Current.GetService<IMyAuthService>();
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            bool auth = myAuthService.IsUserAuthorized();
            if (!auth)
            {
                HandleUnauthorizedRequest(filterContext);
            }
        }
        else
        {
            HandleUnauthorizedRequest(filterContext);
        }
    }
}

Code is written for Unity 3.0 and ASP.NET MVC 4

 
Leave a comment

Posted by on May 29, 2013 in General

 

Tags: , , ,

Dependency Inversion X Inversion Control X Dependency Injection

Dependency Inversion Principle
Definition: Instead of lowel level modules defining an interface that higher level modules depend on, higher level modules define an interface that lower level modules implement.
Example: portable chargeable devices, the copy program (read and write)

Inversion of Control

  • Interface inversion
    The user of the class defines the interface
    Interface should have more than 1 implementation
  • Flow inversion
    Procedural VS Event driven
  • Creation / binding inversion
    Creating objects outside of the class they are being used in.

Dependency Injection
A type of IOC where we move the creation and binding of a dependency outside of the class that depends on it.
Example: packing a lunch VS lunch is provided.

  • Constructor Injection
    Pass dependency into dependent class via constructor.
  • Setter Injection
    Create a setter on the dependent class and use the setter to set the dependency.
  • Interface Injection
    Dependent class implements an interface. Injector uses the interface to set the dependency.
 
Leave a comment

Posted by on July 4, 2012 in References

 

Tags: ,

Dependency Injection Structure

Highly coupled dependency

public class VerySimpleStockTraderImpl : IAutomatedStockTrader
{
    private IStockAnalysisService analysisService = new StockAnalysisServiceImpl();
    private IOnlineBrokerageService brokerageService = new NewYorkStockExchangeBrokerageServiceImpl();

    public void executeTrades()
    {
        for (String stockSymbol : brokerageService.getStockSymbols())
        {
             double askPrice = brokerageService.getAskingPrice(stockSymbol);
             double estimatedValue = analysisService.getEstimatedValue(stockSymbol);
             if (askPrice < estimatedValue)
             {
                  brokerageService.putBuyOrder(stockSymbol, 100, askPrice);
             }
        }
    }
}

public class MyApplication
{
    public static void main(String[] args)
    {
        IAutomatedStockTrader stockTrader = new VerySimpleStockTraderImpl();
        stockTrader.executeTrades();
    }
}

Manually injected dependency

public class VerySimpleStockTraderImpl : IAutomatedStockTrader
{
    private IStockAnalysisService analysisService;
    private IOnlineBrokerageService brokerageService;

    public VerySimpleStockTraderImpl(IStockAnalysisService analysisService, IOnlineBrokerageService brokerageService)
    {
        this.analysisService = analysisService;
        this.brokerageService = brokerageService;
    }

    public void executeTrades()
    {
        ....
    }
}

public class MyApplication
{
    public static void main(String[] args)
    {
        IStockAnalysisService analysisService = new StockAnalysisServiceImpl();
        IOnlineBrokerageService brokerageService = new NewYorkStockExchangeBrokerageServiceImpl();

        IAutomatedStockTrader stockTrader = new VerySimpleStockTraderImpl(analysisService, brokerageService);
        stockTrader.executeTrades();
    }
}

Automatically injected dependency

public class VerySimpleStockTraderImpl : IAutomatedStockTrader
{
    private IStockAnalysisService analysisService;
    private IOnlineBrokerageService brokerageService;

    public VerySimpleStockTraderImpl(IStockAnalysisService analysisService, IOnlineBrokerageService brokerageService)
    {
        this.analysisService = analysisService;
        this.brokerageService = brokerageService;
    }

    public void executeTrades()
    {
        ....
    }
}

public class MyApplication
{
    public static void main(String[] args)
    {
        IAutomatedStockTrader stockTrader = (IAutomatedStockTrader)DependencyManager.create(typeof(IAutomatedStockTrader));
        stockTrader.executeTrades();
    }
}

Source: Wikipedia

 
Leave a comment

Posted by on April 13, 2012 in References

 

Tags: ,

What is Dependency Injection?

Martin Fowler original coined the term in his article, “Inversion of Control Containers and the Dependency Injection pattern”. In it, he explains in great details his approach in creating high cohesive application with weak coupling modules. It’s a design pattern that allows a separate assembler module to inject the implementation into a class. The author derived Dependency Injection from Inversion of Controller for a more specific name for this pattern.

In my simple definition, dependency injection is a concept to move dependency between classes / controls / methods / interfaces by place this dependency in a configuration files (such as xml-based config file).

Before the dependency injection time, developers achieve weak coupling by manually injected dependency in a new class. This new class is responsible for bridging the other two classes. This approach introduces new problem such as, when modifications need to be done in the code, the code will need to be recompiled.

Scott Hanselman has a good list of .Net Containers that can be found here.

Another good read for Dependency Injection term is from Wikipedia.

 
Leave a comment

Posted by on March 21, 2011 in General

 

Tags: , , ,

 
%d bloggers like this: