dotnet webapi学习小结

dotnet webapi学习小结

  1. 由框架根据相应数据库的表自动生成实体类与上下文
dotnet ef dbContext scaffold "server=127.0.0.1;database=mytest;uid=root;pwd=123456" Pomelo.EntityFrameworkCore.MySql -o Entities
  1. 跨域设置
    ①builder.Services.AddCors(c => c.AddPolicy(“any”, p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()));
    ②app.UseCors();
    ③[EnableCors(“any”)]
    public class TestController : ControllerBase

  2. 注意数据库的表名最好还是进行大写由框架自动生成的实体类及ef core的跟踪均为大写状态。

  3. ef core是默认开启实体类数据自动跟踪的,此举对性能消耗极大,最好自行进行取消。
    ①局部数据跟踪关闭

var test = codeFContext.Test.AsNoTracking().FirstOrDefault(x => x.Id == 1);

②生命周期中取消数据跟踪(context生命周期内)


context.ChangeTracker.QueryTrackingBehavior =QueryTrackingBehavior.NoTracking;

③全局设置免跟踪(在注册上下文时对于option进行如下操作)

builder.Services.AddDbContext<CodeFContext>(
option =>
{
// 全局设置context免跟踪
option.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
option.UseMySQL(configuration.GetConnectionString("MysqlDbConn_CodeFirst"));
 }
 );
  1. 上下文注册注意单例陷阱(使用Scoped作用域,每次请求生成独立上下文与数据库形成单独的连接)
    ①对于update等操作在跟踪时若还没有跟踪完即上下文还没有释放时再此请求跟踪同一ID实体则跟踪失败
    ②前端同时访问两个数据(两个异步请求),即第一个数据还有没拿到时,第二个就开始请求拿数据,由于上下文单例已被占用。出现请求数据错误。

  2. dotnet自带的容器注册context服务

var configuration = builder.Configuration;
builder.Services.AddDbContext<CodeFContext>(option => 
option.UseMySQL(configuration.GetConnectionString("MysqlDbConn_CodeFirst"))
);

  1. autofac容器注册服务与controller层的属性注入配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using agvsystem.Config;
using agvsystem.Entities;
using agvsystem.Service;
using agvsystem.Service.IService;
using Autofac;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace agvsystem.common
{
public static class AutofacExtensions
{
public static void AddAutofacApiModule(this ContainerBuilder builder)
{
builder.RegisterType<MapService>().As<IMapService>();
builder.RegisterType<MyMapService>().As<IMyMapService>().PropertiesAutowired();
//MytestContexts上下文交给efcore容器管理
{
IConfiguration config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
String? ConnectStr = config.GetConnectionString("MysqlDbConn_CodeFirst");
builder.Register(c =>
{
var options = new DbContextOptionsBuilder<MytestContext>()
.UseMySql(ConnectStr, ServerVersion.AutoDetect(ConnectStr))
.Options;
return new MytestContext(options);
}).As<MytestContext>().InstancePerLifetimeScope();

}
//注册每个控制器和抽象之间的关系
//找到所有的controller进行注册,并使用属性注入功能
var controllerBaseType = typeof(ControllerBase);
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
.Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
.PropertiesAutowired(new CustomPropertySelector());//支持属性注入

}
}
}

  1. 注解实现controller层的属性注入
// 注解类
namespace agvsystem.Config
{
[AttributeUsage(AttributeTargets.Property)]
internal class AutowiredAttribute:Attribute
{
}
}

// autofac需要的实现了IPropertySelector的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Autofac.Core;

namespace agvsystem.Config
{
public class CustomPropertySelector : IPropertySelector
{
public bool InjectProperty(PropertyInfo propertyInfo,object instance){
return propertyInfo.CustomAttributes.Any(c => c.AttributeType == typeof(AutowiredAttribute));
}
}
}


  • 18
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值