Removing Autofac dependency

This commit is contained in:
Pranav K 2015-10-03 11:57:35 -07:00
parent 6185b16795
commit 8d7b95655d
17 changed files with 1 additions and 414 deletions

13
Mvc.sln
View File

@ -35,8 +35,6 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "ActivatorWebSite", "test\We
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "InlineConstraintsWebSite", "test\WebSites\InlineConstraintsWebSite\InlineConstraintsWebSite.xproj", "{EA34877F-1AC1-42B7-B4E6-15A093F40CAE}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "AutofacWebSite", "test\WebSites\AutofacWebSite\AutofacWebSite.xproj", "{07C0E921-FCBB-458C-AC11-3D01CE68B16B}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.AspNet.Mvc.TestConfiguration", "test\WebSites\Microsoft.AspNet.Mvc.TestConfiguration\Microsoft.AspNet.Mvc.TestConfiguration.xproj", "{680D75ED-601F-4D86-B01B-1072D0C31B8C}"
EndProject
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "RoutingWebSite", "test\WebSites\RoutingWebSite\RoutingWebSite.xproj", "{42CDBF4A-E238-4C0F-A416-44588363EB4C}"
@ -314,16 +312,6 @@ Global
{EA34877F-1AC1-42B7-B4E6-15A093F40CAE}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{EA34877F-1AC1-42B7-B4E6-15A093F40CAE}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{EA34877F-1AC1-42B7-B4E6-15A093F40CAE}.Release|x86.ActiveCfg = Release|Any CPU
{07C0E921-FCBB-458C-AC11-3D01CE68B16B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{07C0E921-FCBB-458C-AC11-3D01CE68B16B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{07C0E921-FCBB-458C-AC11-3D01CE68B16B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{07C0E921-FCBB-458C-AC11-3D01CE68B16B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{07C0E921-FCBB-458C-AC11-3D01CE68B16B}.Debug|x86.ActiveCfg = Debug|Any CPU
{07C0E921-FCBB-458C-AC11-3D01CE68B16B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{07C0E921-FCBB-458C-AC11-3D01CE68B16B}.Release|Any CPU.Build.0 = Release|Any CPU
{07C0E921-FCBB-458C-AC11-3D01CE68B16B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{07C0E921-FCBB-458C-AC11-3D01CE68B16B}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{07C0E921-FCBB-458C-AC11-3D01CE68B16B}.Release|x86.ActiveCfg = Release|Any CPU
{680D75ED-601F-4D86-B01B-1072D0C31B8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{680D75ED-601F-4D86-B01B-1072D0C31B8C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{680D75ED-601F-4D86-B01B-1072D0C31B8C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
@ -1143,7 +1131,6 @@ Global
{34DF1487-12C6-476C-BE0A-F31DF1939AE5} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
{DB79BCBA-9538-4A53-87D9-77728E2BAA39} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
{EA34877F-1AC1-42B7-B4E6-15A093F40CAE} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
{07C0E921-FCBB-458C-AC11-3D01CE68B16B} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
{680D75ED-601F-4D86-B01B-1072D0C31B8C} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
{42CDBF4A-E238-4C0F-A416-44588363EB4C} = {16703B76-C9F7-4C75-AE6C-53D92E308E3C}
{5F945B82-FE5F-425C-956C-8BC2F2020254} = {3BA657BF-28B1-42DA-B5B0-1C4601FCF7B1}

View File

@ -1,110 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Autofac.Core;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
namespace MvcSample.Web
{
/// <summary>
/// Summary description for MonitoringMiddlware
/// </summary>
public class MonitoringMiddlware
{
private RequestDelegate _next;
private IServiceProvider _services;
public MonitoringMiddlware(RequestDelegate next, IServiceProvider services)
{
_next = next;
_services = services;
}
public async Task Invoke(HttpContext httpContext)
{
var url = httpContext.Request.Path.Value;
if (url.Equals("/Monitoring/Clear", StringComparison.OrdinalIgnoreCase))
{
MonitoringModule.Clear();
httpContext.Response.ContentType = "text/plain";
var buffer = Encoding.ASCII.GetBytes("Cleared");
httpContext.Response.Body.Write(buffer, 0, buffer.Length);
}
else if (url.Equals("/Monitoring/ActivatedTypes", StringComparison.OrdinalIgnoreCase))
{
var data = ActivatedTypes();
httpContext.Response.ContentType = "text/plain charset=utf-8";
var buffer = Encoding.UTF8.GetBytes(data);
httpContext.Response.Body.Write(buffer, 0, buffer.Length);
}
else
{
await _next(httpContext);
}
}
public string ActivatedTypes()
{
var values = MonitoringModule.InstanceCount.ToArray();
var builder = new StringBuilder();
Array.Sort(values, new InstancesComparer());
foreach (var item in values)
{
builder.AppendLine(GetTypeName(item.Key.Item1) + " " + item.Value);
}
return builder.ToString();
}
private string GetTypeName(Type type)
{
var name = type.Name;
var isArray = false;
if (typeof(Array).IsAssignableFrom(type))
{
isArray = true;
name = ChopLast2(name);
}
var genericArgs = type.GetGenericArguments().Select(t => t.Name).ToArray();
if (genericArgs.Length > 0)
{
name = ChopLast2(name) + "<" + string.Join(",", genericArgs) + ">";
}
if (isArray)
{
name += "[]";
}
return name;
}
private static string ChopLast2(string name)
{
return name.Remove(name.Length - 2);
}
private class InstancesComparer : IComparer<KeyValuePair<Tuple<Type, IComponentLifetime>, int>>
{
public int Compare(KeyValuePair<Tuple<Type, IComponentLifetime>, int> x, KeyValuePair<Tuple<Type, IComponentLifetime>, int> y)
{
return y.Value.CompareTo(x.Value);
}
}
}
}

View File

@ -1,78 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using Autofac;
using Autofac.Core;
namespace MvcSample.Web
{
/// <summary>
/// Summary description for MonitoringModule
/// </summary>
public class MonitoringModule : Module
{
private static ConcurrentDictionary<Tuple<Type, IComponentLifetime>, int> _registrations
= new ConcurrentDictionary<Tuple<Type, IComponentLifetime>, int>();
private static ConcurrentDictionary<Tuple<Type, IComponentLifetime>, object> _instances
= new ConcurrentDictionary<Tuple<Type, IComponentLifetime>, object>();
public static readonly ConcurrentDictionary<Tuple<Type, IComponentLifetime>, int> InstanceCount
= new ConcurrentDictionary<Tuple<Type, IComponentLifetime>, int>();
protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry,
IComponentRegistration registration)
{
registration.Activating += Registration_Activating;
registration.Activated += Registration_Activated;
}
public Tuple<Type, IComponentLifetime> GetKey(IComponentRegistration context)
{
var activator = context.Activator;
var lifeTime = context.Lifetime;
var limitType = context.Activator.LimitType;
var key = new Tuple<Type, IComponentLifetime>(limitType, lifeTime);
return key;
}
private void Registration_Activated(object sender, ActivatedEventArgs<object> e)
{
object instance;
var key = GetKey(e.Component);
if (_instances.TryGetValue(key, out instance))
{
bool same = (e.Instance == instance);
InstanceCount.AddOrUpdate(key, 1, (_, count) => same ? 1 : count + 1);
}
}
private void Registration_Activating(object sender, ActivatingEventArgs<object> e)
{
var key = GetKey(e.Component);
_registrations.AddOrUpdate(key, 1, (k, value) => value + 1);
_instances.GetOrAdd(key, e.Instance);
}
private void Registration_Preparing(object sender, PreparingEventArgs e)
{
foreach (var param in e.Parameters)
{
Console.WriteLine(param.ToString());
}
}
public static void Clear()
{
//string count = InstanceCount.Select(kvp => kvp.Value).Aggregate((c, n) => c + n).ToString() + " instances from " + InstanceCount.Count + " types";
InstanceCount.Clear();
_instances.Clear();
_registrations.Clear();
// return count;
}
}
}

View File

@ -2,15 +2,10 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Autofac;
using Autofac.Framework.DependencyInjection;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Razor;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Dnx.Runtime;
using MvcSample.Web.Filters;
using MvcSample.Web.Services;
@ -18,8 +13,6 @@ namespace MvcSample.Web
{
public class Startup
{
private bool _autoFac;
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddCaching();
@ -36,40 +29,8 @@ namespace MvcSample.Web
services.AddSingleton<PassThroughAttribute>();
services.AddSingleton<UserNameService>();
services.AddTransient<ITestService, TestService>();
var applicationEnvironment = services.BuildServiceProvider().GetRequiredService<IApplicationEnvironment>();
var configurationPath = Path.Combine(applicationEnvironment.ApplicationBasePath, "config.json");
// Set up configuration sources.
var configBuilder = new ConfigurationBuilder()
.AddJsonFile(configurationPath)
.AddEnvironmentVariables();
var configuration = configBuilder.Build();
var diSystem = configuration["DependencyInjection"];
if (!string.IsNullOrEmpty(diSystem) &&
diSystem.Equals("AutoFac", StringComparison.OrdinalIgnoreCase))
{
_autoFac = true;
// Create the autofac container
var builder = new ContainerBuilder();
// Create the container and use the default application services as a fallback
builder.Populate(services);
builder.RegisterModule<MonitoringModule>();
var container = builder.Build();
return container.Resolve<IServiceProvider>();
}
else
{
return services.BuildServiceProvider();
}
return services.BuildServiceProvider();
}
public void Configure(IApplicationBuilder app)
@ -77,10 +38,6 @@ namespace MvcSample.Web
app.UseStatusCodePages();
app.UseFileServer();
if (_autoFac)
{
app.UseMiddleware<MonitoringMiddlware>();
}
app.UseRequestLocalization();
app.UseSession();

View File

@ -7,7 +7,6 @@
"warningsAsErrors": true
},
"dependencies": {
"Autofac.Framework.DependencyInjection": "4.0.0-beta6-110",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNet.Diagnostics": "1.0.0-*",
"Microsoft.AspNet.Localization": "1.0.0-*",

View File

@ -1,31 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.AspNet.Mvc.FunctionalTests
{
public class DependencyResolverTests : IClassFixture<MvcTestFixture<AutofacWebSite.Startup>>
{
public DependencyResolverTests(MvcTestFixture<AutofacWebSite.Startup> fixture)
{
Client = fixture.Client;
}
public HttpClient Client { get; }
[Theory]
[InlineData("http://localhost/di", "<p>Builder Output: Hello from builder.</p>")]
[InlineData("http://localhost/basic", "<p>Hello From Basic View</p>")]
public async Task AutofacDIContainerCanUseMvc(string url, string expectedResponseBody)
{
// Arrange & Act & Assert (does not throw)
// Make a request to start resolving DI pieces
var responseText = await Client.GetStringAsync(url);
Assert.Equal(expectedResponseBody, responseText);
}
}
}

View File

@ -14,7 +14,6 @@
"AntiforgeryTokenWebSite": "1.0.0",
"ApiExplorerWebSite": "1.0.0",
"ApplicationModelWebSite": "1.0.0",
"AutofacWebSite": "1.0.0",
"BasicWebSite": "1.0.0",
"BestEffortLinkGenerationWebSite": "1.0.0",
"CompositeViewEngineWebSite": "1.0.0",

View File

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>07c0e921-fcbb-458c-ac11-3d01ce68b16b</ProjectGuid>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">..\..\..\artifacts\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">..\..\..\artifacts\bin\$(MSBuildProjectName)\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
<DevelopmentServerPort>49623</DevelopmentServerPort>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DNX\Microsoft.DNX.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@ -1,15 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Mvc;
namespace AutofacWebSite.Controllers
{
public class BasicController : Controller
{
public IActionResult Index()
{
return View();
}
}
}

View File

@ -1,22 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Mvc;
namespace AutofacWebSite.Controllers
{
public class DIController : Controller
{
public DIController(HelloWorldBuilder builder)
{
Builder = builder;
}
public HelloWorldBuilder Builder { get; private set; }
public IActionResult Index()
{
return View(model: Builder.Build());
}
}
}

View File

@ -1,13 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace AutofacWebSite
{
public class HelloWorldBuilder
{
public string Build()
{
return "Hello from builder.";
}
}
}

View File

@ -1,39 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Autofac;
using Autofac.Framework.DependencyInjection;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
namespace AutofacWebSite
{
public class Startup
{
// Set up application services
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient<HelloWorldBuilder>();
var builder = new ContainerBuilder();
builder.Populate(services);
var container = builder.Build();
return container.Resolve<IServiceProvider>();
}
public void Configure(IApplicationBuilder app)
{
app.UseCultureReplacer();
app.UseMvc(routes =>
{
// This default route is for running the project directly.
routes.MapRoute("default", "{controller=DI}/{action=Index}");
});
}
}
}

View File

@ -1 +0,0 @@
<p>Hello From Basic View</p>

View File

@ -1,3 +0,0 @@
@model string
<p>Builder Output: @Model</p>

View File

@ -1,20 +0,0 @@
{
"commands": {
"web": "Microsoft.AspNet.Hosting server=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:5001",
"kestrel": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5000"
},
"dependencies": {
"Autofac.Framework.DependencyInjection": "4.0.0-beta6-110",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-*",
"Microsoft.AspNet.Mvc": "6.0.0-*",
"Microsoft.AspNet.Mvc.TestConfiguration": "1.0.0",
"Microsoft.AspNet.Server.IIS": "1.0.0-*",
"Microsoft.AspNet.Server.WebListener": "1.0.0-*",
"Microsoft.AspNet.StaticFiles": "1.0.0-*"
},
"frameworks": {
"dnx451": { },
"dnxcore50": { }
},
"webroot": "wwwroot"
}

View File

@ -1,4 +0,0 @@
AutofacWebSite
===
This web site illustrates how to use Autofac as the DI container for an MVC application.

View File

@ -1 +0,0 @@
HelloWorld