Could not load file or assembly Microsoft. Web. Infrastructure

If you work on Web Applications and using Asp.Net to power it you may find this error on run time, application might compile perfectly but generates the runtime error stating:

Could not load file or assembly ‘Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. The system cannot find the file specified.

 

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

 

It appears that Microsoft.Web.Infrastructure.dll is not being installed in the GAC, even if .net (4.0 or 4.5 or other) are installed successfully on Windows Server. On localhost (typically Windows client), it seems like it is being in the GAC when the tools/platform (Visual Studio etc.) are installed.

 

Possible Fix 1

Run the following command in the Package Manager Console. (If you are using Visual Studio, this can be reached via menu options “Tools –> Library Package Manager –> Package Manager Console:)

PM> Install-Package Microsoft.Web.Infrastructure

You will see the following messages if it is successfully installed.

Successfully installed ‘Microsoft.Web.Infrastructure 1.0.0.0’.
Successfully added ‘Microsoft.Web.Infrastructure 1.0.0.0’ to Web.

If you see this message you are good to go. Shoop. But in case it does not work try the next one.

 

Possible Fix 2 (Less Technical)

When you do above fix package manager can produce this(non welcoming) message for you:

the package was already installed and assigned to my project.

This is the case when you already have this Microsoft.Web.Infrastructure.dll added in your solution. Go to Window’s explorer and try to search the file by name. Most probably you will find it, copy the path and add it as a reference in project.

Rebuild and Run the project.

Let me know in comments if this does not work or some other solution works for you.

Advertisements

Dependency Injection in ASP.NET Web API 2

What is Dependency Injection?

A dependency is any object that another object requires. For example, it’s common to define a repository that handles data access. Let’s illustrate with an example. First, we’ll define a domain model:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Here is a simple repository class that stores items in a database, using Entity Framework.

public class ProductsContext : DbContext
{
    public ProductsContext()
        : base("name=ProductsContext")
    {
    }
    public DbSet<Product> Products { get; set; }
}

public class ProductRepository : IDisposable
{
    private ProductsContext db = new ProductsContext();

    public IEnumerable<Product> GetAll()
    {
        return db.Products;
    }
    public Product GetByID(int id)
    {
        return db.Products.FirstOrDefault(p => p.Id == id);
    }
    public void Add(Product product)
    {
        db.Products.Add(product);
        db.SaveChanges();
    }

    protected void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (db != null)
            {
                db.Dispose();
                db = null;
            }
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

 

Now let’s define a Web API controller that supports GET requests for Product entities. (I’m leaving out POST and other methods for simplicity.) Here is a first attempt:

public class ProductsController : ApiController
{
    // This line of code is a problem!
    ProductRepository _repository = new ProductRepository();

    public IEnumerable<Product> Get()
    {
        return _repository.GetAll();
    }

    public IHttpActionResult Get(int id)
    {
        var product = _repository.GetByID(id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
}

 

Notice that the controller class depends on ProductRepository, and we are letting the controller create the ProductRepository instance. However, it’s a bad idea to hard code the dependency in this way, for several reasons.

  • If you want to replace ProductRepository with a different implementation, you also need to modify the controller class.
  • If the ProductRepository has dependencies, you must configure these inside the controller. For a large project with multiple controllers, your configuration code becomes scattered across your project.
  • It is hard to unit test, because the controller is hard-coded to query the database. For a unit test, you should use a mock or stub repository, which is not possible with the currect design.

We can address these problems by injecting the repository into the controller. First, refactor the ProductRepository class into an interface:

public interface IProductRepository
{
    IEnumerable<Product> GetAll();
    Product GetById(int id);
    void Add(Product product);
}

public class ProductRepository : IProductRepository
{
    // Implementation not shown.
}

Then provide the IProductRepository as a constructor parameter:

public class ProductsController : ApiController
{
    private IProductRepository _repository;

    public ProductsController(IProductRepository <span class="hiddenGrammarError" pre="">repository)  
    {
        _repository</span> = repository;
    }

    // Other controller methods not shown.
} 

This example uses constructor injection. You can also use setter injection, where you set the dependency through a setter method or property.

But now there is a problem, because your application doesn’t create the controller directly. Web API creates the controller when it routes the request, and Web API doesn’t know anything about IProductRepository. This is where the Web API dependency resolver comes in.

The Web API Dependency Resolver

Web API defines the IDependencyResolver interface for resolving dependencies. Here is the definition of the interface:

public interface IDependencyResolver : IDependencyScope, IDisposable
{
    IDependencyScope BeginScope();
}

public interface IDependencyScope : IDisposable
{
    object GetService(Type serviceType);
    IEnumerable<object> GetServices(Type serviceType);
}

The IDependencyScope interface has two methods:

  • GetService creates one instance of a type.
  • GetServices creates a collection of objects of a specified type.

The IDependencyResolver method inherits IDependencyScope and adds the BeginScope method. I’ll talk about scopes later in this tutorial.

When Web API creates a controller instance, it first calls IDependencyResolver.GetService, passing in the controller type. You can use this extensibility hook to create the controller, resolving any dependencies. If GetService returns null, Web API looks for a parameterless constructor on the controller class.

Dependency Resolution with the Unity Container

Although you could write a complete IDependencyResolver implementation from scratch, the interface is really designed to act as bridge between Web API and existing IoC containers.

An IoC container is a software component that is responsible for managing dependencies. You register types with the container, and then use the container to create objects. The container automatically figures out the dependency relations. Many IoC containers also allow you to control things like object lifetime and scope.

“IoC” stands for “inversion of control”, which is a general pattern where a framework calls into application code. An IoC container constructs your objects for you, which “inverts” the usual flow of control.

For this tutorial, we’ll use Unity from Microsoft Patterns & Practices. (Other popular libraries include Castle Windsor, Spring.Net, Autofac, Ninject, and StructureMap.) You can use NuGet Package Manager to install Unity. From the Tools menu in Visual Studio, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Unity

Here is an implementation of IDependencyResolver that wraps a Unity container.

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;

    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        container.Dispose();
    }
}

If the GetService method cannot resolve a type, it should return null. If the GetServices method cannot resolve a type, it should return an empty collection object. Don’t throw exceptions for unknown types.

Configuring the Dependency Resolver

Set the dependency resolver on the DependencyResolver property of the global HttpConfiguration object.

The following code registers the IProductRepository interface with Unity and then creates a UnityResolver.

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

    // Other Web API configuration not shown.
}

Dependenecy Scope and Controller Lifetime

Controllers are created per request. To manage object lifetimes, IDependencyResolver uses the concept of a scope.

The dependency resolver attached to the HttpConfiguration object has global scope. When Web API creates a controller, it calls BeginScope. This method returns an IDependencyScope that represents a child scope.

Web API then calls GetService on the child scope to create the controller. When request is complete, Web API calls Dispose on the child scope. Use the Dispose method to dispose of the controller’s dependencies.

How you implement BeginScope depends on the IoC container. For Unity, scope corresponds to a child container:

public IDependencyScope BeginScope()
{
    var child = container.CreateChildContainer();
    return new UnityResolver(child);
}

Credit:

Thanks Mike Wasson(Mike Wasson is a programmer-writer at Microsoft) this injection. And yes you originally published this post(which is 100% yours till dinosaur appear again on earth.) on Asp.Net 🙂

How To Learn Coding In One Night?

How to learn coding in one night How to learn coding in one night

So here is the trick “How can I learn coding in a single night?”

Pack a laptop and travel to the north pole in the beginning of winter. You’ll have a 6 months of a night to learn coding.
Once there – really just Google it. There are tons of excellent tutorials on the web.

So you got the answer right. But there is an exception if you are the Robert Downy Jr. that I am amazed to see every-time when he is in his lab.

How to become iron man Iran man can learn anything in one night.

Best of luck with your journey to north pole and get me some ice while coming back!! Cheers.

And on a serious note:

To the point – you can’t learn to write useful code in a single night. Even assuming that you are a highly intelligent person and understand the background disciplines of coding (algorithms, basic I/O etc) you’ll take a few weeks to grasp the complexities of programmatic flow control, principles of adequate design and how to debug when (not if) things go south.

If you like it, you may like our other Hiarious Posts.

Iterate Dictionary Using C#

Dictionary is a object that can store values in Key-Value pair. its just like a list, the only difference is:
List can be iterate using index(0-n) but not the Dictionary.
Generally when we try to iterate the dictionary we get below error:

Collection was modified; enumeration operation may not execute.

So How to parse a dictionary and modify its values??
To iterate dictionary we must loop through it’s keys or key – value pair.

<pre>            //get key collection from dictionary into a list to loop through  	
            List&lt;int&gt; keys = new List&lt;int&gt;(Dictionary.Keys);
            
            // iterating key collection using simple for-each loop
            foreach (int key in keys)
            { 
            	// Now we can perform any modification with values of dictionary.    
            	Dictionary[key] = Dictionary[key] - 1; 
            	
            }</pre>