溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring的事務(wù)管理在C#項(xiàng)目中的實(shí)現(xiàn)

發(fā)布時(shí)間:2024-11-12 18:29:58 來(lái)源:億速云 閱讀:78 作者:小樊 欄目:編程語(yǔ)言

在C#項(xiàng)目中實(shí)現(xiàn)Spring的事務(wù)管理,可以使用.NET的內(nèi)置依賴注入框架和Entity Framework Core來(lái)實(shí)現(xiàn)。以下是一個(gè)簡(jiǎn)單的示例,展示了如何在C#項(xiàng)目中實(shí)現(xiàn)Spring風(fēng)格的事務(wù)管理。

1. 創(chuàng)建項(xiàng)目

首先,創(chuàng)建一個(gè)新的C#項(xiàng)目,例如一個(gè)ASP.NET Core Web應(yīng)用程序。

2. 添加依賴

csproj文件中添加必要的依賴項(xiàng):

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.0" />
  </ItemGroup>

</Project>

3. 配置數(shù)據(jù)庫(kù)上下文

創(chuàng)建一個(gè)繼承自DbContext的類(lèi),并配置數(shù)據(jù)庫(kù)連接字符串:

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }

    public DbSet<User> Users { get; set; }
}

appsettings.json文件中配置數(shù)據(jù)庫(kù)連接字符串:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

4. 配置依賴注入

Startup.cs文件中配置依賴注入:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting.Internal;
using Microsoft.EntityFrameworkCore;

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddScoped<IUserService, UserService>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

5. 實(shí)現(xiàn)服務(wù)層

創(chuàng)建一個(gè)服務(wù)層來(lái)處理業(yè)務(wù)邏輯:

using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

public interface IUserService
{
    Task<User> CreateUserAsync(User user);
}

public class UserService : IUserService
{
    private readonly ApplicationDbContext _context;

    public UserService(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<User> CreateUserAsync(User user)
    {
        _context.Users.Add(user);
        await _context.SaveChangesAsync();
        return user;
    }
}

6. 使用事務(wù)管理

在控制器中使用事務(wù)管理:

using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly IUserService _userService;

    public UsersController(IUserService userService)
    {
        _userService = userService;
    }

    [HttpPost]
    public async Task<IActionResult> CreateUser([FromBody] User user)
    {
        using (var transaction = await _userService.CreateUserAsync(user))
        {
            return CreatedAtAction(nameof(GetUser), new { id = transaction.Id }, transaction);
        }
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetUser(int id)
    {
        var user = await _userService.GetUserAsync(id);
        if (user == null)
        {
            return NotFound();
        }
        return Ok(user);
    }
}

7. 配置EF Core工具

Program.cs文件中配置EF Core工具:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
using Microsoft.Extensions.Hosting;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

var host = app.Run();

// Configure the DbContext to use a transaction per request
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString)
        .UseInternalServiceProvider((context, services) =>
        {
            var serviceProvider = new ServiceCollection()
                .AddDbContext<ApplicationDbContext>(options)
                .BuildServiceProvider();
            return serviceProvider;
        }));

host.Run();

通過(guò)以上步驟,你可以在C#項(xiàng)目中實(shí)現(xiàn)Spring風(fēng)格的事務(wù)管理。這個(gè)示例展示了如何使用Entity Framework Core和依賴注入來(lái)處理事務(wù)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI