分类目录归档:ASP.NET Core

ASP.NET CORE中的IOC注册类的三种方式

AddSingleton():

When we use the AddSingleton() method to register a service, then it will create a singleton service. It means a single instance of that service is created and that singleton instance is shared among all the components of the application that require it. That singleton service is created when we requested for the first time.

AddScoped():

Scoped means instance per request. When we use the AddScoped() method to register a service, then it will create a Scoped service. It means, an instance of the service is created once per each HTTP request and uses that instance in other calls of the same request.

AddTransient():

When we use the AddTransient() method to register a service, then it will create a Transient service. It means a new instance of the specified service is created each time when it is requested and they are never shared.

Note: In the real-time applications, you need to register the components such as application-wide configuration as Singleton. The Database access classes like Entity Framework contexts are recommended to be registered as Scoped so that the connection can be re-used. If you want to run anything in parallel then it is better to register the component as Transient.


Singleton:每次获取的时候,都是同一个实例,相当于静态类

生命周期:项目启动——项目关闭

AddSingleton可以直接用圆括号添加一个实例

Transient: 每次从容器中获取的时候,都是一个新的实例

生命周期:GC回收,主动释放

Scoped: 对象在请求是才开始创建,在这次请求中获取的对象都是同一个

生命周期:请求开始——请求结束

scoped在同一次请求中,获取多次对象得到的是同一个对象

对于同一个接口的多个实现或静态类,最后注册的实现可替换之前的

asp.net core上传文件

public class BannerController : Controller
{

        private ApplicationDbContext _db;
        private IHostingEnvironment _environment;   
        public BannerController(ApplicationDbContext db, IHostingEnvironment environment)
        {
            _db = db;
            _environment = environment;
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(BannerCreateViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var file = viewModel.PicFile;
                var uploads = Path.Combine(_environment.WebRootPath, "uploads/images");
                var ext = Path.GetExtension(file.FileName);//获得文件扩展名
                var timeStamp = DateTimeOffset.Now.ToUnixTimeSeconds();
                var saveName = $"{timeStamp}{ext}";//实际保存文件名
                using (var fileStream = new FileStream(Path.Combine(uploads, saveName), FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
                viewModel.Pic = saveName;
                var model = Mapper.Map<BannerCreateViewModel, Banner>(viewModel);
                _db.Banner.Add(model);
                _db.SaveChanges();
                return RedirectToAction(nameof(Index));
            }
            else
            {
                return View(viewModel);
            }
        }
}


asp.net core显示环境信息

在razor中

@inject Microsoft.Extensions.PlatformAbstractions.IRuntimeEnvironment env
<html>
    <body>
        <img src="images/ASP-NET-Banners-01.png" />
        @("Hello World")
        <footer>
            <div class="container text-center">
                &copy;@DateTime.Now.Year  <a href="http://www.wujie.me">老吴的博客</a> Powered by @($"dotnet-{env.RuntimeType.ToLower()}-{env.RuntimeVersion} on {env.OperatingSystem}")
            </div>
        </footer>
    </body>
</html>