Membuat Dependency Injection dengan ASP.NET Core cukup mudah. Dokumentasinya menjelaskannya dengan sangat baik di sini dan orang ini memiliki killer video untuk menjelaskannya.
Namun, saya ingin melakukan hal yang sama dengan proyek ASP.NET MVC 5 saya. Bagaimana cara menangani dependency injection dengan ASP.MVC 5?
Juga, apakah Dependency injection hanya terbatas pada controllers saja atau dapat bekerja dengan kelas apapun?
Di ASP.Net MVC Anda dapat menggunakan .Net Core DI dari NuGet daripada salah satu alternatif pihak ketiga:-
using Microsoft.Extensions.DependencyInjection
Untuk kelas MVC Start/Configuration: -
public void Configuration(IAppBuilder app)
{
// We will use Dependency Injection for all controllers and other classes, so we'll need a service collection
var services = new ServiceCollection();
// configure all of the services required for DI
ConfigureServices(services);
// Configure authentication
ConfigureAuth(app);
// Create a new resolver from our own default implementation
var resolver = new DefaultDependencyResolver(services.BuildServiceProvider());
// Set the application resolver to our default resolver. This comes from "System.Web.Mvc"
//Other services may be added elsewhere through time
DependencyResolver.SetResolver(resolver);
}
Proyek saya menggunakan Identity User dan saya telah mengganti konfigurasi start-up OWIN untuk mengikuti pendekatan berbasis layanan. Kelas Pengguna Identitas default menggunakan metode pabrik statis untuk membuat instance. Saya telah memindahkan kode tersebut ke dalam konstruktor dan mengandalkan DI untuk menyediakan injeksi yang sesuai. Hal ini masih dalam proses, tetapi di sinilah saya berada: -
public void ConfigureServices(IServiceCollection services)
{
//====================================================
// Create the DB context for the IDENTITY database
//====================================================
// Add a database context - this can be instantiated with no parameters
services.AddTransient(typeof(ApplicationDbContext));
//====================================================
// ApplicationUserManager
//====================================================
// instantiation requires the following instance of the Identity database
services.AddTransient(typeof(IUserStore<ApplicationUser>), p => new UserStore<ApplicationUser>(new ApplicationDbContext()));
// with the above defined, we can add the user manager class as a type
services.AddTransient(typeof(ApplicationUserManager));
//====================================================
// ApplicationSignInManager
//====================================================
// instantiation requires two parameters, [ApplicationUserManager] (defined above) and [IAuthenticationManager]
services.AddTransient(typeof(Microsoft.Owin.Security.IAuthenticationManager), p => new OwinContext().Authentication);
services.AddTransient(typeof(ApplicationSignInManager));
//====================================================
// ApplicationRoleManager
//====================================================
// Maps the rolemanager of identity role to the concrete role manager type
services.AddTransient<RoleManager<IdentityRole>, ApplicationRoleManager>();
// Maps the role store role to the implemented type
services.AddTransient<IRoleStore<IdentityRole, string>, RoleStore<IdentityRole>>();
services.AddTransient(typeof(ApplicationRoleManager));
//====================================================
// Add all controllers as services
//====================================================
services.AddControllersAsServices(typeof(Startup).Assembly.GetExportedTypes()
.Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
.Where(t => typeof(IController).IsAssignableFrom(t)
|| t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));
}
Kelas Account Controller memiliki konstruktor tunggal: -
[Authorize]
public class AccountController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
private RoleManager<IdentityRole> _roleManager;
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, RoleManager<IdentityRole> roleManager)
{
UserManager = userManager;
SignInManager = signInManager;
RoleManager = roleManager;
}
Saya sarankan Anda menggunakan Autofac, ada fwk lain seperti unity, ninject, autofac benchmarks memiliki kinerja yang sangat baik.
http://www.palmmedia.de/blog/2011/8/30/ioc-container-benchmark-performance-comparison
Berikut adalah integrasi dengan MVC (dan bekerja dengan semua kelas)
Cara paling sederhana untuk mengimplementasikan Dependency Injection di ASP.NET MVC 5 adalah dengan menggunakan tool yang dikembangkan oleh Microsoft sendiri, yang disebut Unity
.
Anda dapat menemukan banyak sumber di internet tentang hal ini, dan Anda dapat mulai dengan membaca dokumentasi resmi yang tersedia di sini: Panduan Pengembang untuk Injeksi Ketergantungan Menggunakan Unity
Juga, apakah Dependency injection hanya terbatas pada controllers saja atau dapat bekerja dengan kelas apapun?
Ini dapat bekerja dengan kelas apapun, dalam proyek apapun, selama Anda mendaftarkan Interface yang terkait dengan Implementasi (jika Anda ingin mengambil keuntungan dari IoC pattern), yang harus Anda lakukan adalah menambahkan instantiasi Interface di konstruktor Anda.